//
//  OrganManager.m
//  Messenger
//
//  Created by OC on 15/1/15.
//  Copyright (c) 2015年 YN-APP-iOS. All rights reserved.
//

#import "YNContactManager.h"
#import "YNMessagerReceiveHandle.h"
#import "SynMessageListModel.h"
#import "YNMessage.h"
#import "YNMessagerReceiveHandle.h"
#import "AitContactManagerTool.h"
#import "YNUserTreeRelation.h"
#import "YNContactGroupRelation.h"
#import "YNTwoPeopleChat.h"
#import "YNManyPeopleChat.h"
#import "XMPPDBManager.h"
#import "XMPPFramework.h"
#import "YNOrgTree.h"
#import "YNUser.h"
#import "YNBroadcastChat.h"
#import "YNMessageContactManager.h"
#import "YNBroadcastNotificationChat.h"
#import "FMDatabase.h"
#import "FMDatabaseQueue.h"
#import "FMDatabaseAdditions.h"
#import "YNIMTool.h"
#import "YNIMFrameworkMacro.h"
#import "MessageRemind.h"

#define MESSAGE_BROADCAST @"广播"

@implementation YNContactManager
FMDatabaseQueue *_queue;

FMDatabase *_db;

#pragma mark-删除数据库中所有组织机构，用户，组织机构关系树
+ (BOOL)deleteAllUserAndOrgTree
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    __block BOOL result;
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        
        result =  [YNOrgTree deleteAllOrgTreeDataInDatabase:db];
        
        result =  [YNUserTreeRelation deleteAllUserTreeDataInDatabase:db];
        
        result =  [YNUser deleteAllUserDataInDatabase:db];
        
    }];
    
    
    return result;
}

//2016-9-9jc修改，解决后台删除组织机构，人员后，客服端需要逻辑删除组织机构和人员信息
//先做所有逻辑删除组织机构，人员信息，然后更新到多少组织机构和人员信息再做逻辑更新操作
//逻辑删除数据库中所有组织机构，用户，组织机构关系树
+(BOOL)logicDeleteAllUserAndOrgTree
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    __block BOOL result;
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        //        result =  [YNUser logicDeleteAllUserDataInDatabase:db];
        //        result =  [YNUserTreeRelation logicDeleteAllUserTreeDataInDatabase:db];
        //        result =  [YNOrgTree logicDeleteAllOrgTreeDataInDatabase:db];
        
        result=[YNUser deleteAllUserDataInDatabase:db];
        
        result = [YNUserTreeRelation deleteAllUserTreeDataInDatabase:db];
        
        result = [YNOrgTree deleteAllOrgTreeDataInDatabase:db];
        
    }];
    
    
    return result;
}


#pragma mark- 组织机构
/**
 *  @brief保存所有组织机构
 *
 *  @param orgTreeArray
 */
+ (void)saveAllDataOfOrgTree:(NSArray *)orgTreeArray inDatabase:(FMDatabase *)db
{
    //插入数据
    for (int i=0;i<orgTreeArray.count;i++)
    {
        NSDictionary*orgDic=orgTreeArray[i];
        YNOrgTree *orgTree = [[YNOrgTree alloc] init];
        if (![YNIMTool isEmptyDictionary:orgDic]) {
            [orgTree setValuesForKeysWithDictionary:orgDic];
            //        [self insertOrUpdateDataOfOrgTree:orgTree inDatabase:db];
            [orgTree insertInDatabase:db];
            
        }
        
    }
    
}

/**
 *  @brief  插入或更新一条组织机构记录
 *
 *  @param orgTree orgTree 组织机构
 *  @param db
 *
 *  @return YES执行成功 NO 失败
 */
+ (BOOL)insertOrUpdateDataOfOrgTree:(YNOrgTree *)orgTree inDatabase:(FMDatabase *)db
{
    //判断组织机构是否存在
    //    BOOL isOrgTreeExist = [orgTree isOrgTreeExistInDatabase:db];
    
    //2016-9-9jc修改
    BOOL isOrgTreeExist = [orgTree logicIsOrgTreeExistInDatabase:db];
    
    BOOL result;
    if (isOrgTreeExist)
    {
        result = [orgTree updateInDatabase:db];
    }
    else
    {
        result = [orgTree insertInDatabase:db];
    }
    
    return result;
}

/**
 *  @brief 根据parentOrgNo获取组织机构
 *
 *  @param parentOrgNo 父节点
 *
 *  @return 结果按照ordId降序排列
 */
+ (NSArray *)queryOrgTreeByParentOrgNo:(NSString *)parentOrgNo
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    __block NSArray *orgTreeArray;;
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        orgTreeArray = [YNOrgTree queryByParentOrgNo:parentOrgNo database:db];
        
        dispatch_semaphore_signal(semaphore);
    }];
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    return orgTreeArray;
}


/**
 根据userNo获取本条消息
 
 @param userNo
 @return
 */
+ (NSArray *)queryRecentChatWithUserNo:(NSString *)userNo
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    __block NSArray *orgTreeArray;;
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        orgTreeArray = [YNRecentChatObejct queryRecentChatWithUserNo:userNo inDatabase:db];
        
        dispatch_semaphore_signal(semaphore);
    }];
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    return orgTreeArray;
}

/**
 根据packId获取本条消息
 
 @param packId
 @return
 */
+ (NSArray *)queryRecentChatWithPackId:(NSString *)packId
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    __block NSArray *orgTreeArray;;
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        orgTreeArray = [YNRecentChatObejct queryRecentChatWithPackId:packId inDatabase:db];
        
        dispatch_semaphore_signal(semaphore);
    }];
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    return orgTreeArray;
}

/**
 删除最近会话列表里的所有系统和通知消息
 
 @return
 */
+ (BOOL)deleteRecentSystemAndInformChat
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    __block BOOL result;
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        result = [YNRecentChatObejct deleteRecentSystemAndInformChatWithdatabase:db];
        
        dispatch_semaphore_signal(semaphore);
    }];
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    return result;
}
/**
 根据parentOrgNo获取所有组织机构
 
 @param parentOrgNo 父节点
 @return
 */
+ (NSArray *)queryAllOrgTreeByParentOrgNo:(NSString *)parentOrgNo
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    __block NSArray *orgTreeArray;;
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        orgTreeArray = [YNOrgTree queryAllByParentOrgNo:parentOrgNo database:db];
        
        dispatch_semaphore_signal(semaphore);
    }];
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    return orgTreeArray;
}

/**
 根据parentOrgNo获取联系人中的班级
 
 @param parentOrgNo 父节点
 @return
 */
+ (NSArray *)queryControllerOrgTreeByParentOrgNo:(NSString *)parentOrgNo getAllStudent:(BOOL)allStudent
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    __block NSArray *orgTreeArray;;
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        orgTreeArray = [YNOrgTree queryControllerByParentOrgNo:parentOrgNo getAllStudent:allStudent database:db];
        
        dispatch_semaphore_signal(semaphore);
    }];
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    return orgTreeArray;
}

/**
 根据parentOrgNoStringS获取联系人中的班级,可分页查询

 @param parentOrgNoS 父层级组织机构id集合字符串
 @param start 分页查询开始的索引
 @param length 分页查询数据长度
 @return 组织机构数据集合
 */
+ (NSArray *)queryControllerByOrgNoStringS:(NSString*)parentOrgNoS limitStart:(NSUInteger)start limitLength:(NSUInteger)length getAllStudent:(BOOL)allStudent;
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    __block NSArray *orgTreeArray;
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        orgTreeArray = [YNOrgTree queryControllerByOrgNoStringS:parentOrgNoS getAllStudent:allStudent limitStart:start limitLength:length database:db];
        
        dispatch_semaphore_signal(semaphore);
    }];
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    return orgTreeArray;
}

/**
 根据parentOrgNo获取组织机构中的组织机构
 
 @param parentOrgNo 父节点
 @return
 */
+ (NSArray *)queryOrganizationOrgTreeByParentOrgNo:(NSString *)parentOrgNo
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    __block NSArray *orgTreeArray;
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        orgTreeArray = [YNOrgTree queryOrganizationByParentOrgNo:parentOrgNo database:db];
        
        dispatch_semaphore_signal(semaphore);
    }];
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    return orgTreeArray;
}

/**
 根据parentOrgNo获取组织机构中的组织机构
 老师-联系人-学生界面-查询实习活动
 
 @param parentOrgNo 父节点
 @return
 */
+ (NSArray *)queryOrganizationOrgTreeInternshipByParentOrgNo:(NSString *)parentOrgNo
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    __block NSArray *orgTreeArray;
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        orgTreeArray = [YNOrgTree queryOrganizationInternshipByParentOrgNo:parentOrgNo database:db];
        
        dispatch_semaphore_signal(semaphore);
    }];
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    return orgTreeArray;
}



/**
 *  @brief  判断组织机构是否存在
 *
 *  @param organNo 组织机构ID
 *
 *  @return YES 存在 NO 不存在
 */
+ (BOOL)whetherTheOrganTreeExists:(NSString *)organNo
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    __block BOOL result;
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        YNOrgTree *orgTree = [[YNOrgTree alloc] init];
        orgTree.orgNo = organNo;
        
        result =  [orgTree isOrgTreeExistInDatabase:db];
        
    }];
    
    
    return result;
    
    
}
/**
 获取组织机构数据库数据的条数，也相当于判断其是否有数据

 @return 数据数
 */
+ (NSUInteger)getOrgTreeDataCountInDatabase
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    __block NSUInteger result;
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        result =  [YNOrgTree getOrgTreeDataCountInDatabase:db];
    }];
    return result;
}

#pragma mark- 用户列表

/**
 *  @brief 保存所有用户
 *
 *  @param userArray
 */
+ (void)saveAllDataOfUser:(NSArray *)userArray inDatabase:(FMDatabase *)db
{
    //插入数据
    for (int i=0; i<userArray.count; i++) {
        NSDictionary *userDic=userArray[i];
        YNUser *user = [[YNUser alloc] init];
        if (![YNIMTool isEmptyDictionary:userDic]) {
            [user setValuesForKeysWithDictionary:userDic];
            if ([YNIMTool isEmptyString:user.userId]) {
                user.userId = [YNIMTool getUseridFormImId:user.userNo];
            }
            [user insertInDatabase:db];
            
        }
        
    }
    
}

/**
 *  @brief 插入或更新一条用户信息
 *
 *  @param user 用户信息
 *
 *  @return YES执行成功 NO 失败
 */
+ (BOOL)insertOrUpdateDataOfUser:(YNUser *)user inDatabase:(FMDatabase *)db
{
    //判断用户是否存在
    BOOL isUserExist = [user isUserExistInDatabase:db];
    BOOL result;
    if ([YNIMTool isEmptyString:user.userId]) {
        user.userId = [YNIMTool getUseridFormImId:user.userNo];
    }
    if (isUserExist)
    {
        result = [user updateInDatabase:db];
    }
    else
    {
        result = [user insertInDatabase:db];
    }
    
    return result;
}
/**
 *  @brief  更新用户信息
 *
 *  @param user 用户信息
 *
 *  @return YES 成功 NO 失败
 */
+ (BOOL)updateUserInformation:(YNUser *)user
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    dispatch_semaphore_t Semaphore = dispatch_semaphore_create(0);
    __block BOOL result;
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback)
     {
         result = [self insertOrUpdateDataOfUser:user inDatabase:db];
         dispatch_semaphore_signal(Semaphore);
     }];
    dispatch_semaphore_wait(Semaphore, DISPATCH_TIME_FOREVER);
    return result;
}
/**
 *  @brief 获取当前用户
 *
 */
+ (YNUser *)queryCurrentUser
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    __block YNUser *adminUser;
    dispatch_semaphore_t Semaphore = dispatch_semaphore_create(0);
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        adminUser =  [[YNUser queryUserByUserNo:[YNIMmanager sharedInstance].userImId database:db] lastObject];
        dispatch_semaphore_signal(Semaphore);
    }];
    
    dispatch_semaphore_wait(Semaphore, DISPATCH_TIME_FOREVER);
    return adminUser;
}

//根据用户imID查询用户
+ (YNUser *)queryUserWithUserNo:(NSString *)userNo
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    __block YNUser *user;
    dispatch_semaphore_t Semaphore = dispatch_semaphore_create(0);
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        user =  [[YNUser queryUserByUserNo:userNo database:db] lastObject];
        dispatch_semaphore_signal(Semaphore);
    }];
    
    dispatch_semaphore_wait(Semaphore, DISPATCH_TIME_FOREVER);
    
    return user;
    
}

//根据用户ID查询用户
+ (YNUser *)queryUserWithUserId:(NSString *)userId
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    __block YNUser *user;
    dispatch_semaphore_t Semaphore = dispatch_semaphore_create(0);
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        user =  [[YNUser queryUserByUserId:userId database:db] lastObject];
        dispatch_semaphore_signal(Semaphore);
    }];
    
    dispatch_semaphore_wait(Semaphore, DISPATCH_TIME_FOREVER);
    
    return user;
    
}

/**
 *  @brief 获取所有学生信息用户
 *
 *  @return 所有学生信息用户
 */
+ (NSArray *)queryAllStudentUser
{
    __block NSArray *allUserArray;
    
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    dispatch_semaphore_t querySemaphore = dispatch_semaphore_create(0);
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        allUserArray = [YNUser queryAllStudentUserInDatabase:db];
        
        dispatch_semaphore_signal(querySemaphore);
    }];
    
    dispatch_semaphore_wait(querySemaphore, DISPATCH_TIME_FOREVER);
    
    return allUserArray;
    
}


/**
 *  @brief 获取所有老师信息用户
 *
 *  @return 所有老师信息用户
 */
+ (NSArray *)queryAllTeacherUser
{
    __block NSArray *allUserArray;
    
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    dispatch_semaphore_t querySemaphore = dispatch_semaphore_create(0);
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        allUserArray = [YNUser queryAllTeacherStudentUserInDatabase:db];
        
        dispatch_semaphore_signal(querySemaphore);
    }];
    
    dispatch_semaphore_wait(querySemaphore, DISPATCH_TIME_FOREVER);
    
    return allUserArray;
    
}


/**
 *  @brief  查询用户所在组织机构
 *
 *  @param userNo 用户ID
 *
 *  @return
 */
+ (YNOrgTree *)queryOrgByUserNo:(NSString *)userNo
{
    YNUser *user = [[YNUser alloc] init];
    user.userNo = userNo;
    __block YNOrgTree *orgTree;
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    dispatch_semaphore_t Semaphore = dispatch_semaphore_create(0);
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        orgTree = [[user queryOrgNoByUserNoInDatabase:db] lastObject];
        dispatch_semaphore_signal(Semaphore);
    }];
    dispatch_semaphore_wait(Semaphore, DISPATCH_TIME_FOREVER);
    return orgTree;
}

#pragma mark- 用户机构关系
/**
 *  @brief保存所有用户机构关系
 *
 *  @param userTreeRelArray
 */
+ (void)saveAllDataOfUserTreeRelation:(NSArray *)userTreeRelArray inDatabase:(FMDatabase *)db
{
    //插入数据
    for (int i=0;i<userTreeRelArray.count;i++)
    {
        NSDictionary*relDic=userTreeRelArray[i];
        YNUserTreeRelation *userRelation = [[YNUserTreeRelation alloc] init];
        if (![YNIMTool isEmptyDictionary:relDic]) {
            [userRelation setValuesForKeysWithDictionary:relDic];
            //        [self insertOrUpdateDataOfUserTreeRelation:userRelation inDatabase:db];
            [userRelation insertInDatabase:db];
            
        }
    }
    
}

/**
 *  @brief 插入或更新一条用户组织机构关系
 *
 *  @param userTreeRelation 用户机构关系
 */
+ (BOOL)insertOrUpdateDataOfUserTreeRelation:(YNUserTreeRelation *)userTreeRelation inDatabase:(FMDatabase *)db
{
    BOOL isUserTreeRelationExist = [userTreeRelation isUserTreeRelationExistInDatabase:db];
    BOOL result;
    if (isUserTreeRelationExist)
    {
        result = [userTreeRelation updateInDatabase:db];
    }
    else
    {
        result = [userTreeRelation insertInDatabase:db];
    }
    return result;
}


/**
 *  @brief 根据组织机构ID获取组织机构下的用户
 *
 *  @param orgNo 组织机构ID
 *
 *  @return 组织机构下的用户
 */
+ (NSArray *)queryUsersByOrgNo:(NSString *)orgNo
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    __block NSArray *userArray;
    
    dispatch_semaphore_t querySemaphore = dispatch_semaphore_create(0);
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        userArray = [YNUserTreeRelation queryUserByOrgNo:orgNo database:db];
        
        dispatch_semaphore_signal(querySemaphore);
        
    }];
    
    dispatch_semaphore_wait(querySemaphore, DISPATCH_TIME_FOREVER);
    
    return userArray;
}

/**
 *  @brief 根据组织机构ID获取组织机构下的用户
 不包含老师
 *
 *  @param orgNo 组织机构ID
 *
 *  @return 组织机构下的用户
 */
+ (NSArray *)queryUsersNotTeacherByOrgNo:(NSString *)orgNo
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    __block NSArray *userArray;
    
    dispatch_semaphore_t querySemaphore = dispatch_semaphore_create(0);
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        userArray = [YNUserTreeRelation queryUserNotTeacherByOrgNo:orgNo database:db];
        
        dispatch_semaphore_signal(querySemaphore);
        
    }];
    
    dispatch_semaphore_wait(querySemaphore, DISPATCH_TIME_FOREVER);
    
    return userArray;
}


#pragma mark- 用户在线信息
/**
 *  保存所有用户在线信息
 *
 *  @param userStatusArray
 */
+ (BOOL)updateAllUserStatus:(NSDictionary *)statusDic
{
    NSArray *statusArray = [statusDic objectForKey:@"statusList"];
    
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    __block BOOL result;
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        //插入数据
        for (NSDictionary *dic in statusArray)
        {
            @autoreleasepool
            {
                
                YNUser *user = [[YNUser alloc] init];
                user.userNo = [dic objectForKey:@"userNo"];
                NSArray *resourcesArray = [dic objectForKey:@"resources"];
                
                
                for (NSDictionary *resourceDic in resourcesArray)
                {
                    NSString *resourceString = [resourceDic objectForKey:@"resource"];
                    
                    if ([resourceString isEqualToString:kResource_Msg_Phone])
                    {
                        user.phoneStatus = kResource_Online_Phone_PC;
                    }
                    else if ([resourceString isEqualToString:kResource_Msg_PC])
                    {
                        user.pcStatus =kResource_Online_Phone_PC;
                    }
                }
                
                result = [self updateUserStatus:user updatePcStatus:YES updatePhoneStatus:YES inDatabase:db];
            }
        }
        
        //将当前用户状态设置为在线
        YNUser *currentUser = [[YNUser alloc] init];
        currentUser.userNo = [YNIMmanager sharedInstance].userImId;
        currentUser.phoneStatus = kResource_Online_Phone_PC;
        result = [self updateUserStatus:currentUser updatePcStatus:YES updatePhoneStatus:YES inDatabase:db];
    }];
    
    return result;
}

/**
 *  @brief 更新一条用户在线信息
 *
 *  @param userStatus 用户在线信息
 */
+ (BOOL)updateUserStatus:(YNUser *)user updatePcStatus:(BOOL)pcStatus updatePhoneStatus:(BOOL)phoneStatus inDatabase:(FMDatabase *)db
{
    BOOL isUserExist = [user isUserExistInDatabase:db];
    BOOL result = NO;
    if (isUserExist)
    {
        result = [user updateUserStatusInDatabase:db updatePcStatus:pcStatus updatePhoneStatus:phoneStatus];
    }
    return result;
}

/**
 *  @brief 更新一条用户头像url
 *
 *  @param user 用户对象
 */
+ (BOOL)updateUserheadUrl:(YNUser *)user inDatabase:(FMDatabase *)db
{
    BOOL isUserExist = [user isUserExistInDatabase:db];
    BOOL result = NO;
    if (isUserExist)
    {
        result = [user updateUserheadUrlInDatabase:db];
    }
    return result;
}

//更新用户状态
+ (BOOL)updateUserStatus:(YNUser *)user updatePcStatus:(BOOL)pcStatus updatePhoneStatus:(BOOL)phoneStatus
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    __block BOOL result;
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        result = [self updateUserStatus:user updatePcStatus:pcStatus updatePhoneStatus:phoneStatus inDatabase:db];
        
    }];
    
    return result;
}

//更新用户头像url
+ (BOOL)updateUserheadUrl:(YNUser *)user
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    __block BOOL result;
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        result = [self updateUserheadUrl:user inDatabase:db];
        
    }];
    return result;
}

/**
 *  @brief  离线时清除所有用户在线状态
 *
 *  @return YES 执行成功 NO 失败
 */
+ (BOOL)clearUserOnlineStatusAtTheTimeOfOffline
{
    FMDatabaseQueue *queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    __block BOOL result;
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    
    dispatch_async(dispatch_queue_create("clearOnlineStatus", NULL), ^{
        
        [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
            
            result = [YNUser deleteUserOnlineStatusInDatabase:db];
            
        }];
        
        dispatch_semaphore_signal(semaphore);
        
    });
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    return result;
}

#pragma mark- 查询parentOrgNo节点下面的用户或部门

/**
 @brief 根据parentOrgNo节点查询下面的用户或部门
 
 @param parentOrgNo 组织机构的上级ID，等于0时为根节点
 @param orgType 查询组织机构类型（1：查询所有，2：查询联系人班级，3：查询组织机构下面信息）
 @param allStudent 当上一个参数为contactOrgType时用此参数 yes：查询所有班级数据 NO:查询2-行政班、3-教学班
 @param needAllCount 是否需要计算总人数
 @param needOnlinCount 是否需要计算在线人数
 @param needAllUsers 是否需要返回组织机构下的所有user对象
 @param parentOrgNoS 多个父节点一并查询的父ID字符串
 @param start 分页查询需要的开始行节点
 @param lench 分页查询需要的一次获取数据的条数
 @param countBlock 在分线程里完成总共和在线人数统计的回调
 @return 包含用户或部门的字典
 */
+ (NSDictionary *)queryContactOrgByParentOrgNo:(NSString *)parentOrgNo orgType:(OrgType)orgType getAllStudentDataS:(BOOL)allStudent needCalcuAllCount:(BOOL)needAllCount needCalcuOnlineCount:(BOOL)needOnlinCount needAllUsers:(BOOL)needAllUsers orgNoStringS:(NSString*)parentOrgNoS limitStart:(NSUInteger)start limitLength:(NSUInteger)length completeCount:(void(^)(void))countBlock
{
    NSMutableDictionary *contactOrgDic = [NSMutableDictionary dictionary];
    
    NSArray *userArray;
    int userType = [YNIMmanager sharedInstance].userType;
    //是老师，同时也是联系人界面
    if(orgType == contactOrgType &&  userType == 1)
    {
        userArray = [self queryUsersNotTeacherByOrgNo:parentOrgNo];
    }
    else
    {
        userArray = [self queryUsersByOrgNo:parentOrgNo];
    }
    
    
    if (userArray.count > 0)
    {
        [contactOrgDic setObject:userArray forKey:@"User"];
    }
    
    NSArray *orgTreeArray ;
    switch (orgType) {
        case 0:
            orgTreeArray = [self queryAllOrgTreeByParentOrgNo:parentOrgNo];
            break;
        case 1:
        {
            if (![YNIMTool isEmptyString:parentOrgNoS]) {
                orgTreeArray = [self queryControllerByOrgNoStringS:parentOrgNoS limitStart:start limitLength:length getAllStudent:allStudent];
            }else{
                orgTreeArray = [self queryControllerOrgTreeByParentOrgNo:parentOrgNo getAllStudent:allStudent];
            }
        }
            break;
        case 2:
            orgTreeArray = [self queryOrganizationOrgTreeByParentOrgNo:parentOrgNo];
            break;
        default:
            orgTreeArray = [self queryAllOrgTreeByParentOrgNo:parentOrgNo];
            break;
    }
    
    
    if (orgTreeArray.count > 0)
    {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSArray*blockOrgTreeArray = [NSArray arrayWithArray:orgTreeArray];
            NSDictionary *orgDic = [YNContactManager traverseDepartmentsOfOrganization:orgTreeArray];
            NSMutableArray<YNUser*>*allUsers=[NSMutableArray array];
            for (YNOrgTree *orgTree in blockOrgTreeArray)
            {
                NSArray *tempOrgArray = [orgDic valueForKey:orgTree.orgNo];
                
                int userType = [YNIMmanager sharedInstance].userType;
                
                
                NSMutableString * orgNoStringS = [NSMutableString  string];
                if(![YNIMTool isEmptyString:orgTree.orgNo])
                {
                    [orgNoStringS appendString: [NSString stringWithFormat:@"'%@',",orgTree.orgNo]];
                }
                
                //拼接所有组织机构ID，方便后面查询所有组织机构的用户总数和用户在线总数
                for (YNOrgTree *tempOrgTree in tempOrgArray)
                {
                    if(![YNIMTool isEmptyString:tempOrgTree.orgNo])
                    {
                        [orgNoStringS appendString: [NSString stringWithFormat:@"'%@',",tempOrgTree.orgNo]];
                    }
                }
                orgTree.userCount = 0;
                orgTree.onlineUserCount=0;
                
                //是老师，同时也是联系人界面
                if(orgType == contactOrgType &&  userType == 1)
                {
                    if(![YNIMTool isEmptyString:orgNoStringS])
                    {
                        NSString * orgNos = [orgNoStringS substringToIndex: orgNoStringS.length -1];
                        //计算组织机构的总人数 orgTree.userCount = [self queryUsersCountNotTeacherByOrgNos:orgNos];
                        if (needOnlinCount) {
                            //计算组织机构的在线总人数
                            orgTree.onlineUserCount = [self queryOnlineUsersCountNotTeacherByOrgNos:orgNos];
                        }
                        if (needAllUsers||needAllCount) {
                            //查询组织机构下的所有user
                            NSArray<YNUser*>*users=[self queryAllUsersByOrgNos:orgNos isNoTeacher:YES];
                            
                            if (needAllUsers) {
                                [allUsers addObjectsFromArray:users];
                            }
                            if (needAllCount&&![YNIMTool isEmptyArray:users]) {
                                NSMutableSet<NSString*>* userIdSet=[NSMutableSet set];
                                for (YNUser*tempUser in users) {
                                    if (![YNIMTool isEmptyString:tempUser.userNo]) {
                                        [userIdSet addObject:tempUser.userNo];
                                    }
                                }
                                orgTree.userCount=userIdSet.count;
                            }
                        }
                        
                    }
                }
                //是学生，同时也是联系人界面
                else
                {
                    if(![YNIMTool isEmptyString:orgNoStringS])
                    {
                        NSString * orgNos = [orgNoStringS substringToIndex: orgNoStringS.length -1];
                        //计算组织机构的总人数 orgTree.userCount = [self queryUsersCountByOrgNos:orgNos];
                        if (needOnlinCount) {
                            //计算组织机构的在线总人数
                            orgTree.onlineUserCount = [self queryOnlineUsersCountByOrgNos:orgNos];
                        }
                        if (needAllUsers||needAllCount) {
                            //查询组织机构下的所有user
                            NSArray<YNUser*>*users=[self queryAllUsersByOrgNos:orgNos isNoTeacher:NO];
                            if (needAllUsers) {
                                [allUsers addObjectsFromArray:users];
                            }
                            if (needAllCount&&![YNIMTool isEmptyArray:users]) {
                                NSMutableSet<NSString*>* userIdSet=[NSMutableSet set];
                                for (YNUser*tempUser in users) {
                                    if (![YNIMTool isEmptyString:tempUser.userNo]) {
                                        [userIdSet addObject:tempUser.userNo];
                                    }
                                }
                                orgTree.userCount=userIdSet.count;
                            }
                        }
                        
                    }
                }
            }
            if (needAllUsers) {
                [allUsers addObjectsFromArray:userArray];
            }
            [contactOrgDic setObject:allUsers forKey:@"allUsers"];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (countBlock) {
                    countBlock();
                }
            });
            
        });
        [contactOrgDic setObject:orgTreeArray forKey:@"OrgTree"];
    }else{
        if (needAllUsers) {
            [contactOrgDic setObject:userArray forKey:@"allUsers"];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            if (countBlock) {
                countBlock();
            }
        });
    }
    
    return contactOrgDic;
}

/**
 @brief 根据parentOrgNo节点查询下面的用户或部门
 老师-联系人-学生界面   查询实习活动数据
 
 @param parentOrgNo 组织机构的上级ID，等于0时为根节点
 @param orgType 查询组织机构类型（1：查询所有，2：查询联系人班级，3：查询组织机构下面信息）
 @param needAllCount 是否需要计算总人数
 @param needOnlinCount 是否需要计算在线人数
 @param needAllUsers 是否需要返回组织机构下的所有user对象
 @param countBlock 在分线程里完成总共和在线人数统计的回调
 @return 包含用户或部门的字典
 */
+ (NSDictionary *)queryContactOrgInternshipByParentOrgNo:(NSString *)parentOrgNo orgType:(OrgType)orgType needCalcuAllCount:(BOOL)needAllCount needCalcuOnlineCount:(BOOL)needOnlinCount needAllUsers:(BOOL)needAllUsers completeCount:(void(^)(void))countBlock
{
    NSMutableDictionary *contactOrgDic = [NSMutableDictionary dictionary];
    
    
    NSArray *orgTreeArray ;
    if(orgType == contactOrgType)
    {
        orgTreeArray = [self queryOrganizationOrgTreeInternshipByParentOrgNo:parentOrgNo];
        if (orgTreeArray.count > 0)
        {
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                NSArray*blockOrgTreeArray = [NSArray arrayWithArray:orgTreeArray];
                NSDictionary *orgDic = [YNContactManager traverseDepartmentsOfOrganization:orgTreeArray];
                NSMutableArray<YNUser*>*allUsers=[NSMutableArray array];
                for (YNOrgTree *orgTree in blockOrgTreeArray)
                {
                    NSArray *tempOrgArray = [orgDic valueForKey:orgTree.orgNo];
                    
                    
                    
                    NSMutableString * orgNoStringS = [NSMutableString  string];
                    if(![YNIMTool isEmptyString:orgTree.orgNo])
                    {
                        [orgNoStringS appendString: [NSString stringWithFormat:@"'%@',",orgTree.orgNo]];
                    }
                    
                    //拼接所有组织机构ID，方便后面查询所有组织机构的用户总数和用户在线总数
                    for (YNOrgTree *tempOrgTree in tempOrgArray)
                    {
                        if(![YNIMTool isEmptyString:tempOrgTree.orgNo])
                        {
                            [orgNoStringS appendString: [NSString stringWithFormat:@"'%@',",tempOrgTree.orgNo]];
                        }
                    }
                    orgTree.userCount = 0;
                    orgTree.onlineUserCount=0;
                    
                    
                    if(orgType == contactOrgType)
                    {
                        
                        
                        if(![YNIMTool isEmptyString:orgNoStringS])
                        {
                            int userType = [YNIMmanager sharedInstance].userType;
                            //老师查询时，不包含老师
                            if(userType == 1)
                            {
                                //学生查询时，需要包含老师，学生
                                NSString * orgNos = [orgNoStringS substringToIndex: orgNoStringS.length -1];
                                //计算组织机构的总人数 orgTree.userCount = [self queryUsersCountNotTeacherByOrgNos:orgNos];
                                if (needOnlinCount) {
                                    //计算组织机构的在线总人数
                                    orgTree.onlineUserCount = [self queryOnlineUsersCountNotTeacherByOrgNos:orgNos];
                                }
                                if (needAllUsers||needAllCount) {
                                    //查询组织机构下的所有user
                                    NSArray<YNUser*>*users=[self queryAllUsersByOrgNos:orgNos isNoTeacher:YES];
                                    if (needAllUsers) {
                                        [allUsers addObjectsFromArray:users];
                                    }
                                    if (needAllCount&&![YNIMTool isEmptyArray:users]) {
                                        //计算组织机构的总人数
                                        NSMutableSet<NSString*>* userIdSet=[NSMutableSet set];
                                        for (YNUser*tempUser in users) {
                                            if (![YNIMTool isEmptyString:tempUser.userNo]) {
                                                [userIdSet addObject:tempUser.userNo];
                                            }
                                        }
                                        orgTree.userCount=userIdSet.count;
                                    }
                                }
                            }
                            else
                            {
                                //学生查询时，需要包含老师，学生
                                NSString * orgNos = [orgNoStringS substringToIndex: orgNoStringS.length -1];
                                //计算组织机构的总人数   之前在这一步里通过执行：orgTree.userCount = [self queryUsersCountByOrgNos:orgNos]; 这样的方式计算的
                                if (needOnlinCount) {
                                    //计算组织机构的在线总人数
                                    orgTree.onlineUserCount = [self queryOnlineUsersCountByOrgNos:orgNos];
                                }
                                if (needAllUsers||needAllCount) {
                                    //查询组织机构下的所有user
                                    NSArray<YNUser*>*users=[self queryAllUsersByOrgNos:orgNos isNoTeacher:NO];
                                    if (needAllUsers) {
                                        [allUsers addObjectsFromArray:users];
                                    }
                                    if (needAllCount&&![YNIMTool isEmptyArray:users]) {
                                        NSMutableSet<NSString*>* userIdSet=[NSMutableSet set];
                                        for (YNUser*tempUser in users) {
                                            if (![YNIMTool isEmptyString:tempUser.userNo]) {
                                                [userIdSet addObject:tempUser.userNo];
                                            }
                                        }
                                        orgTree.userCount=userIdSet.count;
                                    }
                                }
                            }

                            
                        }
                    }
                    
                }
                if (needAllUsers) {
                    
                }
                [contactOrgDic setObject:allUsers forKey:@"allUsers"];
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (countBlock) {
                        countBlock();
                    }
                });
                
            });
            [contactOrgDic setObject:orgTreeArray forKey:@"OrgTree"];
        }else{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (countBlock) {
                    countBlock();
                }
            });
        }
        
    }
    
    return contactOrgDic;
}

/**
 计算该组织机构里的总人数数量
 
 @param orgType 类型
 @param parentOrgNo 组织id
 @param allStudent 当 orgType为contactOrgType时有效
 @return 数量
 */
+(NSInteger)calculateOrgTotalUserNumberWithorgType:(OrgType)orgType getAllStudent:(BOOL)allStudent OrgNo:(NSString *)parentOrgNo{
    NSInteger userTotalCount=0;
    NSArray *userArray;
    int userType = [YNIMmanager sharedInstance].userType;
    //是老师，同时也是联系人界面
    if(orgType == contactOrgType &&  userType == 1)
    {
        userArray = [self queryUsersNotTeacherByOrgNo:parentOrgNo];
    }
    else
    {
        userArray = [self queryUsersByOrgNo:parentOrgNo];
    }
    userTotalCount=userArray.count;
    NSArray *orgTreeArray ;
    switch (orgType) {
        case 0:
            orgTreeArray = [self queryAllOrgTreeByParentOrgNo:parentOrgNo];
            break;
        case 1:
            orgTreeArray = [self queryControllerOrgTreeByParentOrgNo:parentOrgNo getAllStudent:allStudent];
            break;
        case 2:
            orgTreeArray = [self queryOrganizationOrgTreeByParentOrgNo:parentOrgNo];
            break;
        default:
            orgTreeArray = [self queryAllOrgTreeByParentOrgNo:parentOrgNo];
            break;
    }
    NSDictionary *orgDic = [YNContactManager traverseDepartmentsOfOrganization:orgTreeArray];
    if (![YNIMTool isEmptyArray:orgTreeArray]) {
        for (YNOrgTree *orgTree in orgTreeArray)
        {
            NSArray *tempOrgArray = [orgDic valueForKey:orgTree.orgNo];
            
            int userType = [YNIMmanager sharedInstance].userType;
            
            NSMutableString * orgNoStringS = [NSMutableString  string];
            if(![YNIMTool isEmptyString:orgTree.orgNo])
            {
                [orgNoStringS appendString: [NSString stringWithFormat:@"'%@',",orgTree.orgNo]];
            }
            //拼接所有组织机构ID，方便后面查询所有组织机构的用户总数和用户在线总数
            for (YNOrgTree *tempOrgTree in tempOrgArray)
            {
                if(![YNIMTool isEmptyString:tempOrgTree.orgNo])
                {
                    [orgNoStringS appendString: [NSString stringWithFormat:@"'%@',",tempOrgTree.orgNo]];
                }
            }
            
            //是老师，同时也是联系人界面
            if(orgType == contactOrgType &&  userType == 1)
            {
                if(![YNIMTool isEmptyString:orgNoStringS])
                {
                    NSString * orgNos = [orgNoStringS substringToIndex: orgNoStringS.length -1];
                    //计算组织机构的总人数
                    userTotalCount += [self queryUsersCountNotTeacherByOrgNos:orgNos];
                }
            }
            //是学生，同时也是联系人界面
            else
            {
                if(![YNIMTool isEmptyString:orgNoStringS])
                {
                    NSString * orgNos = [orgNoStringS substringToIndex: orgNoStringS.length -1];
                    //计算组织机构的总人数
                    userTotalCount += [self queryUsersCountByOrgNos:orgNos];
                }
            }
        }
    }
    return userTotalCount;
}

/**
 根据组织机构ID查询下面的User总数量
 
 @param orgNoString 组织机构ID
 @return <#return value description#>
 */
+ (NSInteger)queryUsersCountByOrgNos:(NSString *)orgNos
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    dispatch_semaphore_t querySemaphore = dispatch_semaphore_create(0);
    
    __block NSInteger tempUserCount;
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        tempUserCount = [YNUserTreeRelation queryUserCountByOrgNos:orgNos database:db];
        
        dispatch_semaphore_signal(querySemaphore);
        
    }];
    
    dispatch_semaphore_wait(querySemaphore, DISPATCH_TIME_FOREVER);
    
    return tempUserCount;
}


/**
 *  @brief  根据组织机构ID查询下面的在线user总数
 *
 *  @param orgNo   组织机构ID
 *  @param userDic 一个包含组织机构下面所有用户的可变字典
 *
 *  @return 一个包含组织机构下面所有用户的可变字典，通过计算字典key的数量计算用户数
 */
+ (NSInteger)queryOnlineUsersCountByOrgNos:(NSString *)orgNos
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    dispatch_semaphore_t querySemaphore = dispatch_semaphore_create(0);
    
    __block NSInteger tempUserCount;
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        tempUserCount = [YNUserTreeRelation queryOnlineUserCountByOrgNos:orgNos database:db];
        
        dispatch_semaphore_signal(querySemaphore);
        
    }];
    
    dispatch_semaphore_wait(querySemaphore, DISPATCH_TIME_FOREVER);
    
    return tempUserCount;
}
/**
 *  @brief  根据组织机构ID查询下面的所有user对象
 *
 *  @param orgNo   组织机构ID
 *
 *  @return YNUser数据数组
 */
+ (NSArray<YNUser*>*)queryAllUsersByOrgNos:(NSString *)orgNos isNoTeacher:(BOOL)noTeacher
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    dispatch_semaphore_t querySemaphore = dispatch_semaphore_create(0);
    
    __block NSArray<YNUser*>* tempUsers;
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        tempUsers=[YNUserTreeRelation queryAllUserByOrgNos:orgNos database:db isNoTeacher:noTeacher];
        
        dispatch_semaphore_signal(querySemaphore);
        
    }];
    
    dispatch_semaphore_wait(querySemaphore, DISPATCH_TIME_FOREVER);
    
    return tempUsers;
}

/**
 根据组织机构ID查询下面的User总数量,不包含老师
 
 @param orgNoString 组织机构ID
 @return <#return value description#>
 */
+ (NSInteger)queryUsersCountNotTeacherByOrgNos:(NSString *)orgNos
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    dispatch_semaphore_t querySemaphore = dispatch_semaphore_create(0);
    
    __block NSInteger tempUserCount;
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        tempUserCount = [YNUserTreeRelation queryUserCountNotTeacherByOrgNos:orgNos database:db];
        
        dispatch_semaphore_signal(querySemaphore);
        
    }];
    
    dispatch_semaphore_wait(querySemaphore, DISPATCH_TIME_FOREVER);
    
    return tempUserCount;
}


/**
 *  @brief  根据组织机构ID查询下面的在线user总数，不包含老师
 *
 *  @param orgNo   组织机构ID
 *  @param userDic 一个包含组织机构下面所有用户的可变字典
 *
 *  @return 一个包含组织机构下面所有用户的可变字典，通过计算字典key的数量计算用户数
 */
+ (NSInteger)queryOnlineUsersCountNotTeacherByOrgNos:(NSString *)orgNos
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    dispatch_semaphore_t querySemaphore = dispatch_semaphore_create(0);
    
    __block NSInteger tempUserCount;
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        tempUserCount = [YNUserTreeRelation queryOnlineUserCountNotTeacherByOrgNos:orgNos database:db];
        
        dispatch_semaphore_signal(querySemaphore);
        
    }];
    
    dispatch_semaphore_wait(querySemaphore, DISPATCH_TIME_FOREVER);
    
    return tempUserCount;
}




/**
 *  @brief  遍历一个父节点下的所有组织机构
 *
 *  @param array 包含一个组织机构直属部门的数组
 *
 *  @return 包含一个组织机构下面所有部门的字典
 */
+ (NSDictionary *)traverseDepartmentsOfOrganization:(NSArray *)orgArray
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    __block NSMutableDictionary *retDic = [NSMutableDictionary dictionary];
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        _db = db;
        
        for (YNOrgTree *orgTree in orgArray)
        {
            NSMutableArray *orArray = [NSMutableArray array];
            NSArray *temp = [self computeOrgNodesByNo:orgTree orgArray:orArray];
            [retDic setObject:temp forKey:orgTree.orgNo];
        }
        
        dispatch_semaphore_signal(semaphore);
    }];
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    return retDic;
}

/**
 *  @brief 根据一个组织机构查询下面直属部门
 *
 *  @param orgTree  一个组织机构
 *  @param orgArray 一个保存组织机构的可变数组
 *
 *  @return 包含一个组织机构下面直属部门的数组
 */
+ (NSArray *)computeOrgNodesByNo:(YNOrgTree *)orgTree orgArray:(NSMutableArray *)orgArray
{
    NSArray *tempOrgTreeArray = [YNOrgTree queryAllByParentOrgNo:orgTree.orgNo database:_db];
    [orgArray addObjectsFromArray:tempOrgTreeArray];
    
    for (YNOrgTree *orgTree in tempOrgTreeArray)
    {
        [self computeOrgNodesByNo:orgTree orgArray:orgArray];
    }
    
    return orgArray;
}


/**
 *  @brief 保存组织机构信息
 *
 *  @param dic
 *
 *  @return YES 执行成功 NO 失败
 */
+ (BOOL)saveContactOrgWithOrgDictionary:(NSDictionary *)dic
{
    NSArray *orgTreeArray = [dic objectForKey:@"orgList"];
    NSArray *userTreeRelArray = [dic objectForKey:@"relList"];
    NSArray *userArray = [dic objectForKey:@"userList"];
    
    __block BOOL result = NO;
    
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        [self saveAllDataOfOrgTree:orgTreeArray inDatabase:db];
        [self saveAllDataOfUserTreeRelation:userTreeRelArray inDatabase:db];
        [self saveAllDataOfUser:userArray inDatabase:db];
        
        result = !*rollback;
    }];
    
    return result;
}

/**
 *  @brief  遍历所有上级组织机构
 *
 *  @param parentOrgNo 父节点
 *
 *  @return
 */
+ (NSMutableArray *)queryAllParentOrgByParentOrgNo:(NSString *)parentOrgNo
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    __block NSMutableArray *orgArray = nil;
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        orgArray = [YNOrgTree queryParentOrgByParentOrgNo:parentOrgNo database:db];
        
    }];
    
    return orgArray;
}
//根据gruoupName查询用户
+ (NSArray *)queryByGruoupName:(NSString *)groupName isAdmin:(BOOL)isAdmin onlyGetTeachers:(BOOL)onlyTeacher{
    
    FMDatabaseQueue *queue = [[XMPPDBManager sharedInstance] achieveQueue];
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    __block NSArray *userArray;
    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        userArray = [YNContactGroupRelation queryByGruoupName:groupName database:db isAdmin:isAdmin onlyGetTeachers:onlyTeacher];
        dispatch_semaphore_signal(semaphore);
    }];
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    return userArray;
}

/**
 *  @brief 保存群组信息
 *
 *  @param N/A
 *
 *  @return YES 执行成功 NO 失败
 */
+ (BOOL)saveContactGroupWithGroupType:(int)groupType orgDictionary:(NSDictionary *)dic
{
    
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    __block BOOL result = NO;
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        NSArray *roomArray = [dic valueForKey:@"roomList"];
        NSArray *userArray = [dic valueForKey:@"userList"];
        
        if (groupType==kContact_DiscussionGropType) {
            //从讨论组的iq数据里将项目组类型赛选出来
            NSMutableArray*discussRoomArray=[NSMutableArray array];
            NSMutableArray*projectRoomArray=[NSMutableArray array];
            for (NSDictionary*roomDic in roomArray) {
                if (![YNIMTool isEmptyDictionary:roomDic]) {
                    NSString*groupName=roomDic[@"groupName"];
                    //判断名字是否以“third”开头的，若是则为项目组数据
                    NSTextCheckingResult*result=[YNIMTool regularMatchingTheString:groupName regularString:@"^(third)"];
                    if (result) {
                        [projectRoomArray addObject:roomDic];
                    }else{
                        [discussRoomArray addObject:roomDic];
                    }
                }
            }
            [self saveAllDataOfGroup:discussRoomArray groupType:kContact_DiscussionGropType inDatabase:db];
            [self saveAllDataOfGroup:projectRoomArray groupType:kContact_ProjectTeamGropType inDatabase:db];
            
            NSMutableArray*discussUserArray=[NSMutableArray array];
            NSMutableArray*projectUserArray=[NSMutableArray array];
            for (NSDictionary*userDic in userArray) {
                if (![YNIMTool isEmptyDictionary:userDic]) {
                    NSString*groupName=userDic[@"groupName"];
                    //判断名字是否以“third”开头的，若是则为项目组数据
                    NSTextCheckingResult*result=[YNIMTool regularMatchingTheString:groupName regularString:@"^(third)"];
                    if (result) {
                        [projectUserArray addObject:userDic];
                    }else{
                        [discussUserArray addObject:userDic];
                    }
                }
            }
            [self saveAllDataOfGroupRelations:discussUserArray groupType:kContact_DiscussionGropType inDatabase:db];
            [self saveAllDataOfGroupRelations:projectUserArray groupType:kContact_ProjectTeamGropType inDatabase:db];
        }else{
            [self saveAllDataOfGroup:roomArray groupType:groupType inDatabase:db];
            [self saveAllDataOfGroupRelations:userArray groupType:groupType inDatabase:db];
        }
    }];
    
    return result;
}




#pragma mark- 群/讨论组信息

/**
 *  @brief 保存群/讨论组信息
 *
 *  @param groupArray
 *  @param groupType
 */
+ (void)saveAllDataOfGroup:(NSArray *)groupArray groupType:(int)groupType inDatabase:(FMDatabase *)db
{
    [YNContactGroup deleteAllDataWithGroupType:groupType database:db];
    for (NSDictionary *dic in groupArray)
    {
        YNContactGroup *group = [[YNContactGroup alloc] init];
        if (![YNIMTool isEmptyDictionary:dic]) {
            [group setValuesForKeysWithDictionary:dic];
        }
        group.groupType = groupType;
        
        [self insertOrUpdateContactGroup:group inDatabase:db];
    }
}

/**
 *  @brief  增量保存群/讨论组所有信息
 *
 *  @param dictionary
 *  @param groupType
 */
+ (BOOL)saveIncrementalGroupDataWithDictionary:(NSDictionary *)dictionary groupType:(int)groupType
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        NSArray *roomArray = [dictionary objectForKey:@"roomList"];
        NSArray *userArray = [dictionary objectForKey:@"userList"];
        
        [self saveIncrementalDataOfGroup:roomArray groupType:groupType inDatabase:db];
        [self saveIncrementalDataOfGroupRelations:userArray groupType:groupType inDatabase:db];
        
        
    }];
    
    return YES;
}

/**
 *  @brief 增量保存群/讨论组信息
 *
 *  @param groupArray
 *  @param groupType
 */
+ (void)saveIncrementalDataOfGroup:(NSArray *)groupArray groupType:(int)groupType inDatabase:(FMDatabase *)db
{
    for (NSDictionary *dic in groupArray)
    {
        YNContactGroup *group = [[YNContactGroup alloc] init];
        if (![YNIMTool isEmptyDictionary:dic]) {
            [group setValuesForKeysWithDictionary:dic];
        }
        group.groupType = groupType;
        [self insertOrUpdateContactGroup:group inDatabase:db];
    }
}

/**
 *  @brief  增量保存群/讨论组-用户关系
 *
 *  @param groupRelArray 群成员关系数组
 *  @param groupType     关系类型
 *  @param db
 */
+ (void)saveIncrementalDataOfGroupRelations:(NSArray *)groupRelArray groupType:(int)groupType inDatabase:(FMDatabase *)db
{
    
    for (NSDictionary *dic in groupRelArray)
    {
        YNContactGroupRelation *groupRel = [[YNContactGroupRelation alloc] init];
        if (![YNIMTool isEmptyDictionary:dic]) {
            [groupRel setValuesForKeysWithDictionary:dic];
        }
        
        [self insertOrUpdateContactGroupRelations:groupRel inDatabase:db];
    }
}

/**
 *  @brief 插入或更新群/讨论组信息
 *
 *  @param group     群/讨论组数据
 *  @param groupType 0:群 1: 讨论组
 *
 *  @return YES 执行成功 NO 失败
 */
+ (BOOL)insertOrUpdateContactGroup:(YNContactGroup *)group inDatabase:(FMDatabase *)db
{
    BOOL isContactGroupExist = [group isContactGroupExistInDatabase:db];
    BOOL result;
    if (isContactGroupExist)
    {
        result = [group updateGroupDatabase:db];
    }
    else
    {
        result = [group insertGroupDatabase:db];
        if (result) {
            MessageRemind *remind = [[MessageRemind alloc] init];
            remind.groupID = group.groupName;
            if (![remind isMessageRemindExistInDatabase:db])
            {
                remind.isRemind = 1;
                
                [remind insertInDatabase:db];
            }
        }
    }
    return result;
}


// 判断群组/讨论组是否存在
+(BOOL)isContactGroupExistIn:(NSString *)groupName groupType:(int)groupType
{
    YNContactGroup *group = [[YNContactGroup alloc] init];
    
    group.groupName = groupName;
    group.groupType = groupType;
    __block BOOL result = NO;
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        result = [group isContactGroupExistInDatabase:db];
        
    }];
    
    return result;
}




/**
 *  @brief  查询群管理员
 *
 *  @param groupName 群ID
 *
 *  @return
 */
+ (NSArray *)queryContactGroupAdministratorByGroupName:(NSString *)groupName
{
    NSArray *adminArray = [self queryUserByGroupName:groupName isAdmin:YES onlyGetTeachers:NO];
    return adminArray;
}

/**
 *  @brief  更新群/讨论组信息
 *
 *  @param groupType 0:群 1:讨论组
 *  @param group 群/讨论组对象
 *  @return
 */
+ (BOOL)updateContactGroup:(YNContactGroup *)group
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    __block BOOL result;
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        result = [group updateGroupDatabase:db];
        
        if (result)
        {
            result = [YNRecentChatObejct updateRecentChatTitle:group.subject byUserNo:group.groupName inDatabase:db];
        }
    }];
    
    return result;
}
/**
 *  @brief  获取用户群/讨论组列表信息
 *
 *  @param groupType 0:群 1:讨论组
 *  @param onlyTeacher 只查询老师的数据
 *  @return 返回群/讨论组数组
 */
+ (NSArray *)queryContactGroup:(int)groupType onlyGetTeachers:(BOOL)onlyTeacher
{
    
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    dispatch_semaphore_t groupSemaphore = dispatch_semaphore_create(0);
    dispatch_semaphore_t memberSemaphore = dispatch_semaphore_create(0);
    
    __block NSArray *groupArray;
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
            
            groupArray = [YNContactGroup queryContactGroupWithGroupType:groupType database:db];
            
        }];
        dispatch_semaphore_signal(memberSemaphore);
    });
    
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        dispatch_semaphore_wait(memberSemaphore, DISPATCH_TIME_FOREVER);
        
        dispatch_apply([groupArray count], dispatch_get_global_queue(0, 0), ^(size_t index) {
            
            YNContactGroup *contactGroup = [groupArray objectAtIndex:index];
            //获取群，组织机构，讨论组下面的用户
            contactGroup.memberArray = [self queryUserByGroupName:contactGroup.groupName isAdmin:NO onlyGetTeachers:onlyTeacher];
            //2018-11-8JC添加，获取群，组织机构，讨论组下面的在线用户数量
            contactGroup.onlineCount = [self queryUserOnlineCountByGroupName:contactGroup.groupName isAdmin:NO onlyGetTeachers:onlyTeacher];
        });
        
        dispatch_semaphore_signal(groupSemaphore);
    });
    
    dispatch_semaphore_wait(groupSemaphore, DISPATCH_TIME_FOREVER);
    
    return groupArray;
}

//查询讨论组创建者
+ (NSArray<NSString*> *)queryCreatorOfDiscussionGroup
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    __block NSArray *creatorArray;
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        creatorArray = [YNContactGroupRelation queryCreatorOfDiscussionGroupInDatabase:db];
        
    }];
    
    return creatorArray;
}



/**
 *  @brief  根据群/讨论组ID获取群/讨论组信息
 *
 *  @param groupNo   群/讨论组ID
 *  @param groupType
 *
 *  @return
 */
+ (YNContactGroup *)queryGroupByGroupNo:(NSString *)groupNo groupType:(int)groupType
{
    
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    __block YNContactGroup *group;
    
    dispatch_semaphore_t groupSemaphore = dispatch_semaphore_create(0);
    dispatch_semaphore_t memberSemaphore = dispatch_semaphore_create(0);
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
            
            NSArray *groupArray = [YNContactGroup queryContactGroupByGroupName:groupNo database:db];
            
            group = [groupArray firstObject];
            
        }];
        dispatch_semaphore_signal(memberSemaphore);
    });
    
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        dispatch_semaphore_wait(memberSemaphore, DISPATCH_TIME_FOREVER);
        
        group.memberArray = [self queryUserByGroupName:group.groupName isAdmin:NO onlyGetTeachers:NO];
        
        dispatch_semaphore_signal(groupSemaphore);
    });
    
    dispatch_semaphore_wait(groupSemaphore, DISPATCH_TIME_FOREVER);
    
    return group;
    
}

#pragma mark- 用户与群/讨论组关系

/**
 *  @brief 保存群/讨论组关系信息
 *
 *  @param groupRelArray
 *  @param groupType
 */
+ (void)saveAllDataOfGroupRelations:(NSArray *)groupRelArray groupType:(int)groupType inDatabase:(FMDatabase *)db
{
    [YNContactGroupRelation deleteAllDataWithGroupType:groupType database:db];
    for (NSDictionary *dic in groupRelArray)
    {
        YNContactGroupRelation *groupRel = [[YNContactGroupRelation alloc] init];
        if (![YNIMTool isEmptyDictionary:dic]) {
            [groupRel setValuesForKeysWithDictionary:dic];
        }
        
        [self insertOrUpdateContactGroupRelations:groupRel inDatabase:db];
    }
}


/**
 *  @brief 插入或更新用户与群/讨论组关系
 *
 *  @param groupRelation 用户与群/讨论组关系信息
 *  @param groupType 0: 群 1: 讨论组
 *
 *  @return YES 执行成功 NO 失败
 */
+ (BOOL)insertOrUpdateContactGroupRelations:(YNContactGroupRelation *)groupRelation inDatabase:(FMDatabase *)db
{
    BOOL isGroupRelExist = [groupRelation isContactGroupRelExistInDatabase:db];
    BOOL result;
    if (isGroupRelExist)
    {
        result = [groupRelation updateWithGroupDatabase:db];
    }
    else
    {
        result = [groupRelation insertWithGroupDatabase:db];
    }
    
    return result;
}


/**
 *  @brief 根据群/讨论组Id获取下面的用户
 *
 *  @param groupName 群/讨论组Id
 *  @param groupType 0:群 1:讨论组
 *  @param isAdmin YES 是管理员 NO不是
 *  @param onlyTeacher 只获取老师的数据
 *  @return 一个群/讨论组的成员数组
 */
+ (NSArray *)queryUserByGroupName:(NSString *)groupName isAdmin:(BOOL)isAdmin onlyGetTeachers:(BOOL)onlyTeacher
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    __block NSArray *userArray;
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        userArray = [YNContactGroupRelation queryByGruoupName:groupName database:db isAdmin:isAdmin onlyGetTeachers:onlyTeacher];
        
        dispatch_semaphore_signal(semaphore);
    }];
    
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    return userArray;
}

/**
 *  @brief 根据群/讨论组/项目组Id计算下面用户的在线人数
 *
 *  @param groupName 群/讨论组/项目组Id
 *  @param groupType 0:群 1:讨论组
 *  @param isAdmin YES 是管理员 NO不是
 *  @param onlyTeacher 只获取老师数据
 *  @return 一个群/讨论组/项目组的成员数组
 */
+(NSInteger)queryUserOnlineCountByGroupName:(NSString *)groupName isAdmin:(BOOL)isAdmin onlyGetTeachers:(BOOL)onlyTeacher
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    __block NSInteger onlineCount;
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        onlineCount = [YNContactGroupRelation queryUserOnlineCountByGruoupName:groupName database:db isAdmin:isAdmin onlyGetTeachers:onlyTeacher];
        
        dispatch_semaphore_signal(semaphore);
    }];
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    return onlineCount;
}

/**
 查询自己在群组里的角色（是否是管理员）
 
 @param groupType
 @return 结果集
 */
+ (NSArray<NSDictionary*> *)queryMyGroupRoleWithGroupId:(NSString*)groupId
{
    __block NSArray*result;
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        result = [YNContactGroupRelation queryMyGroupRoleWithGroupId:groupId database:db];
        
        dispatch_semaphore_signal(semaphore);
    }];
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    return result;
}


/**
 *  @brief 创建讨论组
 *
 *  @param group 讨论组信息
 *  @param memberArray 讨论组成员数组
 *
 *  @return YES 执行成功 NO 失败
 */
+ (BOOL)createDiscussionGroup:(YNContactGroup *)group memberArray:(NSArray *)memberArray
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    __block BOOL result;
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        group.groupType = CurrenChatObjType_discussion;
        result = [self insertOrUpdateContactGroup:group inDatabase:db];
        
        if (result)
        {
            result = [self addMemberForCreateGroup:group.groupName memberArray:memberArray inDatabase:db];
        }
    }];
    
    return result;
}

/*!
 *  @author 李健, 15-04-23 14:04:54
 *
 *  @brief  添加讨论组成员
 *
 *  @param group       讨论组对象
 *  @param memberArray 要添加的成员数组
 *
 *  @return
 */
+ (BOOL)addGroupMemberWithGroup:(YNContactGroup *)group addMemberArray:(NSArray *)memberArray
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    __block BOOL result;
    dispatch_semaphore_t groupSemaphore = dispatch_semaphore_create(0);
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        for (NSString *userNo in memberArray)
        {
            YNContactGroupRelation *groupRel = [[YNContactGroupRelation alloc] init];
            groupRel.userNo = userNo;
            groupRel.groupName = group.groupName;
            result = [self insertOrUpdateContactGroupRelations:groupRel inDatabase:db];
        }
        
        dispatch_semaphore_signal(groupSemaphore);
    }];
    
    dispatch_semaphore_wait(groupSemaphore, DISPATCH_TIME_FOREVER);
    
    return result;
}



/**
 *  @brief 创建讨论组时添加讨论组成员
 *
 *  @param memberArray 讨论组成员
 *  @param groupName   讨论组名称
 *
 *  @return YES 执行成功 NO 失败
 */
+ (BOOL)addMemberForCreateGroup:(NSString *)groupName  memberArray:(NSArray *)memberArray inDatabase:db
{
    BOOL result = NO;
    
    for (int i = 0;i < memberArray.count; i++)
    {
        NSString*userNo = memberArray[i];
        YNContactGroupRelation *groupRel = [[YNContactGroupRelation alloc] init];
        groupRel.userNo = userNo;
        groupRel.groupName = groupName;
        if ([userNo isEqualToString:[YNIMmanager sharedInstance].userImId]) {
            groupRel.role = @"10";
        }else{
            groupRel.role = @"50";
        }
        
        result = [self insertOrUpdateContactGroupRelations:groupRel inDatabase:db];
    }
    
    return result;
}

/**
 *  @brief 解散群/讨论组
 *
 *  @param group 群/讨论组信息
 *
 *  @return YES 执行成功 NO 失败
 */
+ (BOOL)dissolveGroupByGroup:(YNContactGroup *)group
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    __block BOOL result;
    
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        result = [group deleteWithGroupDatabase:db];
        
        @try{
            if (result)
            {
                result = [YNContactGroupRelation deleteByGroupName:group.groupName database:db];
            }
            
            
        }
        @catch (NSException *exception) {
            
            debugLog(@"%s\n%@___%@", __FUNCTION__, exception, @"解散群/讨论组");
        }
        @finally {
            
            
        }
        
    }];
    
    
    return result;
}

/**
 *  @brief 踢出或离开群/讨论组
 *
 *  @param user  群/讨论组成员信息
 *  @param group 群/讨论组信息
 *
 *  @return YES 执行成功 NO 失败
 */
+ (BOOL)leaveGroupWithUser:(YNUser *)user group:(YNContactGroup *)group
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    __block BOOL result;
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        result = [YNContactGroupRelation deleteByGroupName:group.groupName andUserNo:user.userNo database:db];
    }];
    
    
    return result;
}



/**
 *  @brief  判断群/讨论组成员是否存在
 *
 *  @param userNo    成员ID
 *  @param groupName 群/讨论组 ID
 *  @param groupType
 *
 *  @return YES ： 存在  NO ： 不存在
 */
+ (BOOL)whetherGroupOfMembers:(NSString *)userNo withGroupNo:(NSString *)groupName groupType:(int)groupType
{
    YNContactGroup *group = [[YNContactGroup alloc] init];
    
    group.groupName = groupName;
    group.groupType = groupType;
    __block BOOL result = NO;
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        result = [group isContactGroupExistInDatabase:db];
        
        if (result)
        {
            YNContactGroupRelation *groupRel = [[YNContactGroupRelation alloc] init];
            
            groupRel.groupName = group.groupName;
            groupRel.userNo = userNo;
            
            result = [groupRel isContactGroupRelExistInDatabase:db];
        }
    }];
    return result;
}


#pragma mark- 搜索联系人

/**
 *  @brief  搜索联系人
 *
 *  @param  keywords 搜索关键字
 *  @param  onlyTeacher 是否只搜教师相关数据
 *  @param  orgType 搜索的组织机构类型
 *  @return 搜索结果
 */
+ (NSDictionary *)searchContactResultByKeywords:(NSString *)keywords canSearchMe:(BOOL)searchMe onlyGetTeacherData:(BOOL)onlyTeacher orgType:(OrgType)orgType
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    __block NSArray *userArray;
    __block NSArray *orgTreeArray;
    __block NSArray *userGroupArray;
    __block NSArray *discussionGroupArray;
    __block NSArray *projectTeamGroupArray;
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        userArray = [YNUser queryUserByKeywords:keywords canSearchMe:searchMe database:db onlyGetTeacherData:onlyTeacher];
        orgTreeArray = [YNOrgTree queryOrgTreeByKeywords:keywords database:db orgType:orgType];
        userGroupArray = [YNContactGroup queryGroupByKeywords:keywords groupType:kContact_UserGroupType database:db];
        discussionGroupArray = [YNContactGroup queryGroupByKeywords:keywords groupType:kContact_DiscussionGropType database:db];
        projectTeamGroupArray = [YNContactGroup queryGroupByKeywords:keywords groupType:kContact_ProjectTeamGropType database:db];
        
    }];
    
    NSMutableDictionary *resultDic = [NSMutableDictionary dictionary];
    
    if (userArray.count > 0)
    {
        [resultDic setObject:userArray forKey:kContact_User];
    }
    
    if (orgTreeArray.count > 0)
    {
        [resultDic setObject:orgTreeArray forKey:kContact_OrgTree];
    }
    
    if (userGroupArray.count > 0)
    {
        [resultDic setObject:userGroupArray forKey:kContact_UserGroup];
    }
    
    if (discussionGroupArray.count > 0)
    {
        [resultDic setObject:discussionGroupArray forKey:kContact_DiscussionGrop];
    }
    
    if (projectTeamGroupArray.count > 0)
    {
        [resultDic setObject:projectTeamGroupArray forKey:kContact_ProjectTeamGroup];
    }
    return resultDic;
    
}

////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////

#pragma mark ---------------------- 孙浪 ------------------------

#pragma mark - RecentChat Method

/**
 * @brief 保存一条会话 (插入和更新)
 *
 * @param 会话信息
 */
+ (BOOL)saveRecentChatWithMessage:(YNRecentChatObejct *)recentChat isFromRoamingSource:(BOOL)isRoaming
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    __block BOOL result;
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        [self insertOrUpdateRecentChatWithMessage:recentChat inDatabase:db isFromRoamingSource:isRoaming];
        result = *rollback;
        
    }];
    return result;
}

+ (BOOL)insertOrUpdateRecentChatWithMessage:(YNRecentChatObejct *)recentChat inDatabase:(FMDatabase *)db  isFromRoamingSource:(BOOL)isRoaming
{
    
    BOOL isRecentChatExist =  [YNRecentChatObejct determineRecentChatTableWithUserNo:recentChat.userNo Database:db];
    BOOL result;
    
    if (isRecentChatExist) {
        
        if (recentChat.chatType!=YNBubbleMessageChatTypeSystemMessage&&recentChat.chatType!=YNBubbleMessageChatTypeNoticeAnnouncement&&recentChat.chatType!=YNBubbleMessageChatTypeBroadcast) {
            
            if (isRoaming) {
                //获取已存在的这条记录
                YNRecentChatObejct*oldObejct=[YNRecentChatObejct queryRecentChatWithFriendId:recentChat.userNo inDatabase:db];
                //看这条记录是否为草稿状态，若为，则不更新这条记录，继续它的草稿状态
                if (oldObejct.sendState==YNMessageSendStateDraft) {
                    return YES;
                }else{
                    //判断其是否为发送中或者发送失败的状态
                    if (oldObejct.sendState==YNMessageSendStateFailed||oldObejct.sendState==YNMessageSendStateSending) {
                        //判断其时间是否比漫游拉下来的消息的时间新，若新，则继续她的发送失败或发送中状态
                        if ([oldObejct.dataTime compare:recentChat.dataTime options:NSNumericSearch]==NSOrderedDescending) {
                            return YES;
                        }
                    }
                }
            }
        }
        
        result = [recentChat updateRecentChatTableInDatabase:db isFromRoamingSource:isRoaming];
    }
    else
    {
        result = [recentChat insertRecentChatTableInDatabase:db];
    }
    
    return result;
}

/**
 2019-01 修改 查询所有最近会话消息列表数据
 
 @param db <#db description#>
 @param needScreenTop 是否需要赛选处理置顶消息
 @return 集合
 */
+ (NSArray<YNRecentChatObejct*> *)queryAllRecentChatWithNeedScreenTopChat:(BOOL)needScreenTop
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    dispatch_semaphore_t recentChatSemaphore = dispatch_semaphore_create(0);
    
    __block NSArray *recentChatArray;
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback){
        
        recentChatArray = [YNRecentChatObejct queryAllRecentChatTableInDatabase:db needScreenTopChat:needScreenTop];
        dispatch_semaphore_signal(recentChatSemaphore);
    }];
    
    dispatch_semaphore_wait(recentChatSemaphore, DISPATCH_TIME_FOREVER);
    
    return recentChatArray;
}

/**
 * @brief 删除会话
 */
+ (BOOL)deleteRecentChatWithRecentChatObject:(NSString *)UserNo
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    __block BOOL result;
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        if (UserNo != nil)
        {
            //删除一条会话
            result = [YNRecentChatObejct deleteRecentForTableWithUserNo:UserNo ChatType:0 database:db];
        }
        else
        {
            //删除所有会话
            result = [YNRecentChatObejct deleteAllRecentWithDatabase:db];
        }
        
    }];
    
    return result;
}

/**HX** 将userNo未读消息的未读数做加一或减一的更新 **/
+ (BOOL)updateUserUnreadCountByOneWithUserNo:(NSString*)UserNo isAddOne:(BOOL)addOne
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    __block BOOL result;
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        result=[YNRecentChatObejct updateUserUnreadCountByOneWithUserNo:UserNo isAddOne:addOne Database:db];
    }];
    
    return result;
}

/**
 *  @brief  清除聊天记录
 *
 *  @return
 */
+ (BOOL)deleteChatRecord
{
    
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    __block BOOL result;
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        result = [YNTwoPeopleChat deleteAllChatInDatabase:db];
        result = [YNManyPeopleChat deleteAllChatWithGroupType:kContact_UserGroupType inDatabase:db];
        result = [YNManyPeopleChat deleteAllChatWithGroupType:kContact_DiscussionGropType inDatabase:db];
        result = [YNManyPeopleChat deleteAllChatWithGroupType:kContact_ProjectTeamGropType inDatabase:db];
        result = [YNBroadcastChat deleteALLBroadcastInDatabase:db];
        result = *rollback;
    }];
    return result;
    
}

/**
 *  功能: 根据ID查询一条最近会话
 *  return:一个最近会话对象
 */
+ (YNRecentChatObejct *)queryRecentChatWithFriendId:(NSString *)friendId
{
    FMDatabaseQueue *queue = [[XMPPDBManager sharedInstance] achieveQueue];
    __block YNRecentChatObejct *recentChat;
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        recentChat = [YNRecentChatObejct queryRecentChatWithFriendId:friendId inDatabase:db];
        dispatch_semaphore_signal(semaphore);
        
    }];
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    return recentChat;
}

#pragma mark - TwoPeopleChat Method

/**
 * @brief 保存一条消息到历史消息表
 *
 * @param twoPeopleChat 会话消息
 */
+ (BOOL)saveTwoPeopleChatWithMessage:(YNTwoPeopleChat *)twoPeopleChat
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    __block BOOL result;
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        [twoPeopleChat insertTwoPeopleChatTableInDatabase:db];
        result = *rollback;
    }];
    return result;
}

/**
 * @bried 一次保存N条历史消息
 *
 * @param twoPeopleChatArray 消息数组
 */
+ (BOOL)saveMuchTwoPeopleChatWithMessage:(NSArray *)twoPeopleChatArray
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    __block BOOL result = NO;
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback){
        
        for (int messageNumber = 0; messageNumber < twoPeopleChatArray.count; messageNumber++) {
            
            YNTwoPeopleChat *twoPeopleChat = [twoPeopleChatArray objectAtIndex:messageNumber];
            
            [twoPeopleChat insertTwoPeopleChatTableInDatabase:db];
            
        }
        result = *rollback;
        
    }];
    
    return result;
}

/**
 * @brief 清空消息
 *
 * @param UserNo 要清空消息的用户的UserNo, 如果传进来为
 *               nil，清空所有历史消息
 */
+ (BOOL)deleteTwoPeopleChatWithUserNo:(NSString *)UserNo
{
    _queue  = [[XMPPDBManager sharedInstance] achieveQueue];
    __block BOOL result;
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        if (UserNo != nil)
        {
            //清空UserNo的历史消息
            result = [YNTwoPeopleChat deleteTwoPeopleChatWithUserNo:UserNo inDatabase:db];
        }
        else
        {
            //清空所有的历史消息
            result = [YNTwoPeopleChat deleteAllChatInDatabase:db];
        }
        result = *rollback;
        
    }];
    
    return result;
}

/**
 * @brief 查询两人会话历史消息
 *
 * @param UserNo 需要查询的用户的UserNo
 *        start  起始
 *        end    需要返回好多条信息(一般为20)
 */
+ (NSArray *)queryTwoPeopleChatHistoryMessageWithUserNo:(NSString *)UserNo startIndex:(NSInteger)start endIndex:(NSInteger)end
{
    return [self queryTwoPeopleChatHistoryMessageWithUserNo:UserNo startIndex:start endIndex:end isSelectSendSuccessMessage:NO];
}

+ (NSString*)queryMinTimeByTwoPeopleChatWithUserNo:(NSString*)userNO{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    __block NSString* blockString=@"";
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback){
        
        blockString = [YNTwoPeopleChat queryMinTimeByTwoPeopleChatWithUserNo:userNO inDatabase:db];
        dispatch_semaphore_signal(semaphore);
    }];
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    return blockString;
}

//根据userNo查询本条信息
+ (NSArray*)queryTwoPeopleChatWithUserNo:(NSString*)userNO{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    __block NSArray *twoPeopleChatArray;
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback){
        
        twoPeopleChatArray = [YNTwoPeopleChat queryTwoPeopleChatWithUserNo:userNO inDatabase:db];
        dispatch_semaphore_signal(semaphore);
    }];
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    return twoPeopleChatArray;
}

+ (NSArray *)queryTwoPeopleChatHistoryMessageWithUserNo:(NSString *)UserNo startIndex:(NSInteger)start endIndex:(NSInteger)end isSelectSendSuccessMessage:(BOOL)selectSuccess
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    __block NSArray *twoPeopleChatArray;
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback){
        
        twoPeopleChatArray = [YNTwoPeopleChat queryTwoPeopleChatWithUserNo:UserNo
                                                                startIndex:start
                                                                  endIndex:end
                                                isSelectSendSuccessMessage:selectSuccess
                                                                inDatabase:db];
        dispatch_semaphore_signal(semaphore);
    }];
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    return twoPeopleChatArray;
}

/**
 查询两人会话未读第一条信息
 
 @param userNo 聊天信息id
 @param unReadCount 未读条数
 @return 返回数据
 */
+(NSArray *)queryUnReadFirstTwoPeopleChatMessageWithUserNo:(NSString *)userNo unReadCount:(NSInteger)unReadCount
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    __block NSArray *twoPeopleChatArray;
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback){
        
        twoPeopleChatArray = [YNTwoPeopleChat queryUnReadFirstTwoPeopleChatMessageWithUserNo:userNo unReadCount:unReadCount inDatabase:db];
        
        dispatch_semaphore_signal(semaphore);
    }];
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    return twoPeopleChatArray;
}


/**
 用于消息漫游判断
 两人会话查询最近多少条信息
 
 @param UserNo 聊天对方账号
 @param sendTime 这个时间之前的多少条数据，nil：最近多少条数据
 @param numberCount 查询多少条数据
 @return 返回结果
 */
+(NSArray *)queryTwoPeopleChatTopInfoWithUserNo:(NSString *)UserNo mTime:(NSString *)mTime numberCount:(NSInteger)numberCount
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    __block NSArray *twoPeopleChatArray;
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback){
        
        twoPeopleChatArray =[YNTwoPeopleChat queryTwoPeopleChatTopInfoWithUserNo:UserNo mTime:mTime numberCount:numberCount Database:db];
        
        dispatch_semaphore_signal(semaphore);
    }];
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    return twoPeopleChatArray;
}



/**
 用于消息漫游判断
 群、讨论组、项目组、会话查询最近多少条信息
 
 @param groupNo 群、讨论组、项目组id
 @param groupType 类型
 @param sendTime  这个时间之前的多少条数据，nil：最近多少条数据
 @param numberCount 查询多少条数据
 @return 返回结果
 */
+(NSArray *)queryManPeopleChatTopInfoWithGroupNo:(NSString *)groupNo GroupType:(int)groupType mTime:(NSString *)mTime numberCount:(NSInteger)numberCount
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    __block NSArray *twoPeopleChatArray;
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback){
        
        twoPeopleChatArray =[YNManyPeopleChat queryManPeopleChatTopInfoWithGroupNo:groupNo GroupType:groupType mTime:mTime numberCount:numberCount Database:db];
        
        dispatch_semaphore_signal(semaphore);
    }];
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    return twoPeopleChatArray;
}



/**
 用于消息漫游判断
 广播通知查询最近多少条信息
 
 @param mTime 时间
 @param numberCount 查询多少条数据
 @return
 */
+(NSArray *)queryBroadcastChatTopInfomTime:(NSString *)mTime numberCount:(NSInteger)numberCount
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    __block NSArray *broadcastChatArray;
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback){
        
        broadcastChatArray =[YNBroadcastChat queryBroadcastChatTopInfoWithmTime:mTime numberCount:numberCount Database:db];
        
        dispatch_semaphore_signal(semaphore);
    }];
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    return broadcastChatArray;
    
}


+ (NSArray *)queryTwoPeopleChatByKeywords:(NSString *)keyWords withUserNo:(NSString *)userNo
{
    FMDatabaseQueue *queue = [[XMPPDBManager sharedInstance] achieveQueue];
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    __block NSArray *Array;
    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        Array = [YNTwoPeopleChat queryTwoPeopleChatByKeywords:keyWords byUserNo:userNo inDatabase:db];
        dispatch_semaphore_signal(semaphore);
    }];
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    return Array;
}
#pragma mark - ManyPeopleChat Method

/**
 * @brief 保存一条消息到多人历史消息表
 *
 * @param manyPeopleChat 需要保存的消息对象
 * @param groupType      判断是群消息还是讨论组消息
 **/
+ (BOOL)saverManyPeopleChatWithMesage:(YNManyPeopleChat *)manyPeopleChat groupType:(int)groupType
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    __block BOOL result;
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback){
        
        [manyPeopleChat insertManyPeopleChatWithGroupType:groupType inDatabase:db];
        result = *rollback;
    }];
    
    return result;
}

/**
 * @brief 清空消息
 *
 * @param GroupNo   需要清空消息的群或讨论组的GroupNo,如果为NIL，清空所有消息
 *        groupType 判断是群消息还是讨论组消息
 **/
+ (BOOL)deleteManyPeopleChatWithGroupNo:(NSString *)GroupNo groupType:(int)groupType
{
    FMDatabaseQueue *queue = [[XMPPDBManager sharedInstance] achieveQueue];
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    __block BOOL result;
    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        if (GroupNo != nil)
        {
            result = [YNManyPeopleChat deleteManyPeopleChatWithGroupType:groupType groupNo:GroupNo inDatabase:db];
        }
        else
        {
            result = [YNManyPeopleChat deleteAllChatWithGroupType:groupType inDatabase:db];
        }
        dispatch_semaphore_signal(semaphore);
    }];
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    return result;
}

/**
 * @brief 查询duoren会话历史消息
 *
 * @param GroupNo   根据GroupNo查询消息
 *        groupType 判断是群消息还是讨论组消息
 *        start     起始
 *        end       需要返回好多条信息(一般为20)
 **/
+ (NSArray *)queryManyPeopleChatHistoryMessageWithGroupNo:(NSString *)GroupNo groupType:(int)groupType startIndex:(NSInteger)start endIndex:(NSInteger)end
{
    return [self queryManyPeopleChatHistoryMessageWithGroupNo:GroupNo groupType:groupType startIndex:start endIndex:end isSelectSendSuccessMessage:NO];
}

+ (NSArray *)queryManyPeopleChatHistoryMessageWithGroupNo:(NSString *)GroupNo groupType:(int)groupType startIndex:(NSInteger)start endIndex:(NSInteger)end isSelectSendSuccessMessage:(BOOL)selectSuccess
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    __block NSArray *manyPeopleChatArray;
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback){
        
        manyPeopleChatArray = [YNManyPeopleChat queryManyPeopleChatWithGroupTyoe:groupType
                                                                         groupNo:GroupNo
                                                                      startIndex:start
                                                                        endIndex:end
                                                      isSelectSendSuccessMessage:selectSuccess
                                                                      inDatabase:db];
        dispatch_semaphore_signal(semaphore);
    }];
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    return manyPeopleChatArray;
}

/**
 查询多人对话未读消息的第一条消息
 
 @param GroupNo 当前聊天所在的讨论组/项目组或群的ID
 @param groupType 类型
 @param unReadCount 未读消息条数
 @return 返回数据
 */
+ (NSArray *)queryUnReadFirstManyPeopleChatGroupNo:(NSString *)GroupNo groupType:(int)groupType unReadCount:(NSInteger)unReadCount
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    __block NSArray *manyPeopleChatArray;
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback){
        
        manyPeopleChatArray = [YNManyPeopleChat queryUnReadFirstManyPeopleChatGroupNo:GroupNo groupType:groupType unReadCount:unReadCount inDatabase:db];
        dispatch_semaphore_signal(semaphore);
    }];
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    return manyPeopleChatArray;
}

/**
 查询艾特@数据
 2018-11-16 JC添加
 @param groupType
 @param groupNo
 @return 返回结果
 */
+ (NSArray *)queryManyPeopleChatAitWithGroupTyoe:(int)groupType groupNo:(NSString *)groupNo
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    __block NSArray *manyPeopleChatArray;
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback){
        
        manyPeopleChatArray = [YNManyPeopleChat queryManyPeopleChatAitWithGroupTyoe:groupType groupNo:groupNo inDatabase:db];
        dispatch_semaphore_signal(semaphore);
    }];
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    return manyPeopleChatArray;
}

/**
 查询艾特@个人或艾特@所有人，离最新一条数据共有多少条数据
 2018-11-16 JC添加
 
 @param groupType
 @param groupNo
 @param aitContactMark 1：艾特@自己，2：艾特所有人
 @return 返回结果
 */
+ (NSInteger)queryManyPeopleChatAitCountWithGroupTyoe:(int)groupType groupNo:(NSString *)groupNo ynmanyPeopleChat:(YNManyPeopleChat*)ynmanyPeopleChat
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    __block NSInteger aitPeopleChatCount;
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback){
        
        aitPeopleChatCount = [YNManyPeopleChat queryManyPeopleChatAitCountWithGroupTyoe:groupType groupNo:groupNo ynmanyPeopleChat:ynmanyPeopleChat inDatabase:db];
        dispatch_semaphore_signal(semaphore);
    }];
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    return aitPeopleChatCount;
}

/**
 修改艾特@数据为默认0的数据
 2018-11-16 JC添加
 @param groupType
 @param groupNo
 */
+ (BOOL)updateManyPeopleChatAitWithGroupTyoe:(int)groupType groupNo:(NSString *)groupNo
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    __block BOOL returnBool;
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback){
        
        returnBool = [YNManyPeopleChat updateManyPeopleChatAitWithGroupTyoe:groupType groupNo:groupNo inDatabase:db];
        dispatch_semaphore_signal(semaphore);
    }];
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    return returnBool;
}


/**
 * @brief 根据关键字查询历史消息
 *
 * @param keyWords  用户输入的关键字
 *        groupType 判断是群消息还是讨论组消息
 **/
+ (NSArray *)queryManyPeopleChatByKeywords:(NSString *)keyWords groupNo:(NSString *)groupNo groupType:(int)groupType
{
    FMDatabaseQueue *queue = [[XMPPDBManager sharedInstance] achieveQueue];
    //__block BOOL result;
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    __block NSArray *array;
    [queue inTransaction:^(FMDatabase *db, BOOL *rollback){
        array=[YNManyPeopleChat queryManyPeopleChatWithGroupType:groupType ByKeywords:keyWords groupNo:groupNo inDatabase:db];
        dispatch_semaphore_signal(semaphore);
    }];
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    return array;
}

#pragma mark - 根据id获取名字
/**
 * @brief 根据id获取名字
 **/
+ (id)queryUserNameByUserID:(NSString *)userID chatType:(int)chatType
{
    _queue = [[XMPPDBManager sharedInstance] achieveQueue];
    dispatch_semaphore_t queryUserNameSemaphore = dispatch_semaphore_create(0);
    
    __block BOOL result;
    __block id Object;
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback){
        
        if (chatType == YNBubbleMessageChatTypeWeChat || chatType == YNBubbleMessageChatTypeWeChatVoice || chatType == YNBubbleMessageChatTypeFileWeChat)
            
        {
            NSArray *tempArray = [YNUser queryUserByUserNo:userID database:db];
            if (tempArray.count != 0)
            {
                Object = [tempArray objectAtIndex:0];
            }
            else
            {
                Object = nil;
            }
        }
        else if (chatType == YNBubbleMessageChatTypeGroupChat || chatType == YNBubbleMessageChatTypeGroupChatVoice)
        {
            NSArray *tempArray = [YNContactGroup queryContactGroupByGroupName:userID database:db];
            if (tempArray.count != 0)
            {
                Object = [tempArray objectAtIndex:0];
            }
            else
            {
                Object = nil;
            }
        }
        else if (chatType == YNBubbleMessageChatTypeProjectTeamChat || chatType == YNBubbleMessageChatTypeProjectTeamVoice)
        {
            NSArray *tempArray = [YNContactGroup queryContactGroupByGroupName:userID database:db];
            if (tempArray.count != 0)
            {
                Object = [tempArray objectAtIndex:0];
            }
            else
            {
                Object = nil;
            }
        }
        else if (chatType == YNBubbleMessageChatTypeDiscussion || chatType == YNBubbleMessageChatTypeDiscussionVoice)
        {
            NSArray *tempArray = [YNContactGroup queryContactGroupByGroupName:userID database:db];
            
            if (tempArray.count != 0)
            {
                Object = [tempArray objectAtIndex:0];
            }
            else
            {
                Object = nil;
            }
            
        }
        else if (chatType == YNBubbleMessageChatTypeBroadcast)
        {
            Object = nil;
        }
        else
        {
            Object = nil;
        }
        
        result = *rollback;
        dispatch_semaphore_signal(queryUserNameSemaphore);
    }];
    
    dispatch_semaphore_wait(queryUserNameSemaphore, DISPATCH_TIME_FOREVER);
    
    return Object;
}

/**
 解析和保存拉取到的漫游消息
 
 @param infos 消息数组
 @param isNewListPullData YES:消息列表拉取最新消息漫游
 @return 结果
 */
+ (BOOL)parsingAndSaveRoamMessageWithInfo:(NSArray *)infos isMessageListData:(BOOL)isMessageListData isNewListPullData:(BOOL)isNewListPullData{
    BOOL result = NO;
    if (![YNIMTool isEmptyArray:infos]) {
        for (NSDictionary*objDic in infos) {
            if (![YNIMTool isEmptyString:objDic[@"msg"]]) {
                NSString*objStr=objDic[@"msg"];
                //将最后一条消息转为Messenger消息对象
                NSError*error;
                NSXMLElement * element=[[DDXMLElement alloc]initWithXMLString:objStr error:&error];
                if (!error) {
                    XMPPMessage *xmMessage=[XMPPMessage messageFromElement:element];
                    YNMessage*message=[[YNMessage alloc]initWithXMPPMessage:xmMessage messageSourceType:GroupMessageSourceType_Roaming isFromSessionListLastMessage:NO];
                    if (message.chatType==YNBubbleMessageChatTypeDocumentsSent) {
                        /**HX** 过略掉文件p2p发送这条的捂手信息 **/
                        continue;
                    }
                    if (message.chatType!=YNBubbleMessageChatTypeBroadcast) {
                        //消息不为广播消息
                        //将消息分段转成数组, 然后再转成Json字符串保存数据库
                        NSArray *messageArray = [YNMessagerReceiveHandle parserMessageStr:message.text messageBody:message.message];
                        
                        //消息json化
                        if (messageArray.count)
                        {
                            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:messageArray options:NSJSONWritingPrettyPrinted error:nil];
                            message.text = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
                            
                            //判断是不是图文混排
                            BOOL isPic = [[messageArray lastObject] boolValue];
                            if (isPic)
                            {
                                //是就改变消息媒体类型
                                NSUInteger imgCount = [[messageArray objectAtIndex:messageArray.count - 3] integerValue];
                                if (imgCount)
                                {
                                    //是就改变消息媒体类型
                                    message.messageMediaType = YNBubbleMessageMix;
                                }
                                else
                                {
                                    message.messageMediaType = YNBubbleMessageText;
                                }
                            }
                        }
                        else
                        {
                            message.text = [YNIMTool jsonStringWithObject:message.text];
                        }
                        if ([[YNIMmanager sharedInstance].getIdCurrChatWithUser isEqualToString:message.friendId]) {
                            /**HX** 是在与user的聊天页面 **/
                            switch (message.messageMediaType) {
                                case YNBubbleMessageMix:
                                case YNBubbleMessageText:
                                {
                                }
                                    break;
                                case YNBubbleMessagePhoto:
                                {
                                }
                                    break;
                                case YNBubbleMessageFile:
                                {
                                    message.fileState = fileStateNotDownload;
                                }
                                    break;
                                case YNBubbleMessageVoice:
                                {
                                    message.voiceState = voiceStateNotDownload;
                                }
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                    message.isRead = 1;
                    //消息保存到数据库-解析不同类型的会话
                    switch (message.chatType) {
                        case YNBubbleMessageChatTypeWeChat:
                        case YNBubbleMessageChatTypeWeChatVoice:
                        case YNBubbleMessageChatTypeFileWeChat:
                        {
                            //二人会话
                            YNTwoPeopleChat *twoPeopleChat = [[YNTwoPeopleChat alloc] init];
                            twoPeopleChat.packId = message.packetId;
                            twoPeopleChat.chatUserNo = message.friendId;
                            twoPeopleChat.fileId = nil;
                            twoPeopleChat.messageType = message.messageMediaType;
                            twoPeopleChat.isSendMsg = message.sendState;
                            twoPeopleChat.message = message.text;
                            twoPeopleChat.mTime = message.sendTime;
                            twoPeopleChat.isReaded = message.isRead;
                            twoPeopleChat.isSuccess = YNMessageSendStateSuccess;
                            twoPeopleChat.masterType = message.bubbleMessageType;
                            twoPeopleChat.messageBody = message.message;
                            twoPeopleChat.content = message.body;
                            twoPeopleChat.senderName = message.friendName;
                            twoPeopleChat.fileState = fileStateNotDownload;
                            twoPeopleChat.isMessageContinuous=YES;
                            //是消息列表的数据
                            if(isMessageListData)
                            {
                                twoPeopleChat.isMessageContinuous=NO;
                                twoPeopleChat.messageContinuousKey = [YNIMTool getGUID];
                            }
                            //2018-12-10JC添加，增加对消息撤回的判断
                            NSXMLElement * unmark = [element elementForName:@"unmark"];
                            if(unmark != nil)
                            {
                                twoPeopleChat.isMessageWithdraw = YES;
                            }
                            else
                            {
                                twoPeopleChat.isMessageWithdraw = NO;
                            }
                            /**HX** 如果消息类型为文件已读回执，且发送人是自己则要过滤掉这条消息 **/
                            if (message.chatType==YNBubbleMessageChatTypeFileWeChat) {
                                if (![[xmMessage from].user isEqualToString:[YNIMmanager sharedInstance].userImId]) {
                                    result=[YNContactManager saveTwoPeopleChatWithMessage:twoPeopleChat];
                                }
                            }else{
                                result=[YNContactManager saveTwoPeopleChatWithMessage:twoPeopleChat];
                            }
                        }
                            break;
                        case YNBubbleMessageChatTypeGroupChat:
                        case YNBubbleMessageChatTypeDiscussion:
                        case YNBubbleMessageChatTypeGroupChatVoice:
                        case YNBubbleMessageChatTypeDiscussionVoice:
                        case YNBubbleMessageChatTypeProjectTeamChat:
                        case YNBubbleMessageChatTypeProjectTeamVoice:
                        {
                            YNManyPeopleChat *manyPeopleChat = [[YNManyPeopleChat alloc] init];
                            if (isMessageListData) {
                                manyPeopleChat.fromUserNo=[xmMessage from].user;
                                manyPeopleChat.toUserNo=[xmMessage from].user;
                                manyPeopleChat.groupNo = [xmMessage to].user;
                                if ([manyPeopleChat.toUserNo isEqualToString:[YNIMmanager sharedInstance].userImId]) {
                                    manyPeopleChat.masterType = YNBubbleMessageTypeSending;
                                }else{
                                    manyPeopleChat.masterType = YNBubbleMessageTypeReceiving;
                                }
                            }else{
                                manyPeopleChat.fromUserNo=message.fromUserId;
                                manyPeopleChat.toUserNo=message.toUserId;
                                manyPeopleChat.groupNo = message.friendId;
                                manyPeopleChat.masterType = message.bubbleMessageType;
                            }
                            manyPeopleChat.messageType = message.messageMediaType;
                            manyPeopleChat.packetId = message.packetId;
                            manyPeopleChat.fileId = nil;
                            manyPeopleChat.isSendMsg = message.sendState;
                            manyPeopleChat.message = message.text;
                            manyPeopleChat.mTime = message.sendTime;
                            manyPeopleChat.isReaded = message.isRead;
                            manyPeopleChat.isSuccess = YNMessageSendStateSuccess;
                            manyPeopleChat.sendName = message.friendName;
                            manyPeopleChat.messageBody = message.message;
                            manyPeopleChat.content = message.body;
                            manyPeopleChat.fileState = fileStateNotDownload;
                            manyPeopleChat.isMessageContinuous = YES;
                            //是消息列表的数据
                            if(isMessageListData)
                            {
                                manyPeopleChat.isMessageContinuous = NO;
                                manyPeopleChat.messageContinuousKey = [YNIMTool getGUID];
                            }
                            //2018-12-10JC添加，增加对消息撤回的判断
                            NSXMLElement * unmark = [element elementForName:@"unmark"];
                            if(unmark != nil)
                            {
                                manyPeopleChat.isMessageWithdraw = YES;
                            }
                            else
                            {
                                manyPeopleChat.isMessageWithdraw = NO;
                            }
                            if (message.chatType == YNBubbleMessageChatTypeGroupChat || message.chatType == YNBubbleMessageChatTypeGroupChatVoice)
                            {
                                if(isNewListPullData)
                                {
                                    [AitContactManagerTool setAitContactMarkManyPeopleChat:manyPeopleChat groupType:kContact_UserGroupType];
                                }
                                result=[YNContactManager saverManyPeopleChatWithMesage:manyPeopleChat groupType:kContact_UserGroupType];
                            }
                            else if (message.chatType == YNBubbleMessageChatTypeDiscussion || message.chatType == YNBubbleMessageChatTypeDiscussionVoice)
                                
                            {
                                if(isNewListPullData)
                                {
                                    [AitContactManagerTool setAitContactMarkManyPeopleChat:manyPeopleChat groupType:kContact_DiscussionGropType];
                                }
                                result=[YNContactManager saverManyPeopleChatWithMesage:manyPeopleChat groupType:kContact_DiscussionGropType];
                            }
                            else//项目组
                            {
                                if(isNewListPullData)
                                {
                                    [AitContactManagerTool setAitContactMarkManyPeopleChat:manyPeopleChat groupType:kContact_ProjectTeamGropType];
                                }
                                result=[YNContactManager saverManyPeopleChatWithMesage:manyPeopleChat groupType:kContact_ProjectTeamGropType];
                            }
                        }
                            break;
                        case YNBubbleMessageChatTypeBroadcast:
                        {
                            //广播消息
                            NSString *covertStr = [YNMessage covertJsonWithHTML:message.body];
                            NSDictionary *messageBody = (NSDictionary*)[YNIMTool getJsonObjectFromJsonString:covertStr];
                            BOOL isBroadcast=NO;//是否为正确的广播消息
                            if (![messageBody isKindOfClass:[NSDictionary class]]) {
                                isBroadcast=YES;
                            }else{
                                if ([YNIMTool isEmptyObject:messageBody[@"messageType"]]) {
                                    isBroadcast=YES;
                                }else{
                                    //为平台发出的推送消息广播不要做处理
                                    result=YES;
                                }
                            }
                            if (isBroadcast) {
                                //为pc端发的广播需要做处理-广播消息保存到数据库
                                YNBroadcastChat *broadcast = [[YNBroadcastChat alloc] init];
                                broadcast.packetId = message.packetId;
                                broadcast.subject = message.subject;
                                broadcast.fromUserNo = message.fromUserId;
                                broadcast.toUserNo = message.toUserId;
                                broadcast.messageType = 0;
                                //                                broadcast.message = message.text;
                                /**HX** 添加广播附件时的修改 **/
                                broadcast.message=message.message;
                                broadcast.mTime = message.sendTime;
                                broadcast.senderName = message.friendName;
                                broadcast.recipient = nil;
                                broadcast.headerUrl = message.avatarUrl;
                                broadcast.isRead=NO;
                                broadcast.isMessageContinuous = YES;
                                if(isMessageListData)
                                {
                                    broadcast.isMessageContinuous = NO;
                                    broadcast.messageContinuousKey = [YNIMTool getGUID];
                                }
                                broadcast.isRead = [[YNIMmanager sharedInstance]broadcastUnreadsHaveId:broadcast.packetId];
                                result=[YNMessageContactManager saveBroadcastWithMessage:broadcast];
                            }
                        }
                            break;
                        default:
                        {
                            
                            debugLog(@"其他类型消息");
                        }
                            break;
                    }
                }
            }
        }
    }else{
        //拉取到的漫游消息数据为空
    }
    
    return result;
}

/**
 * 将同步的消息列表数据保存到数据库
 * pram: array 消息列表数据集合
 */
+ (BOOL)saveSessionListWithInfo:(NSArray *)infos
{
    BOOL result = NO;
    //将消息列表显示的这条消息还有保存聊天记录表一份，创建一个数组装message消息体，然后将他们保存
    NSMutableArray*chatRecordArr=[NSMutableArray array];
    if (![YNIMTool isEmptyArray:infos]) {
        for (NSDictionary*objDic in infos) {
            if (![YNIMTool isEmptyDictionary:objDic]) {
                
                SynMessageListModel*synListModel=[[SynMessageListModel alloc]init];
                [synListModel setValuesForKeysWithDictionary:objDic];
                //将最后一条消息转为Messenger消息对象
                NSError*error;
                NSXMLElement * element=[[DDXMLElement alloc]initWithXMLString:synListModel.lastMsg error:&error];
                if (!error) {
                    XMPPMessage *xmMessage=[XMPPMessage messageFromElement:element];
                    YNMessage*YNmsg=[[YNMessage alloc]initWithXMPPMessage:xmMessage messageSourceType:GroupMessageSourceType_Roaming isFromSessionListLastMessage:YES];
                    switch (YNmsg.chatType) {
                        case YNBubbleMessageChatTypeWeChat:
                        case YNBubbleMessageChatTypeWeChatVoice:
                        case YNBubbleMessageChatTypeFileWeChat:
                        {
                            //二人会话
                            //先检查当前用户id在本地能查到人不，不能查到说明该人已经离职或是从数据库删除了
                            YNUser *user = [YNIMmanager queryUserWithUserNo:YNmsg.friendId];
                            if ([YNIMTool isEmptyObject:user]) {
                                //清除本地存的最近会话数据库数据
                                [YNContactManager deleteRecentChatWithRecentChatObject:YNmsg.friendId];
                            }else{
                                YNRecentChatObejct *recentChat= [YNMessagerReceiveHandle creatRecentChat:YNmsg];
                                recentChat.title = recentChat.senderName;
                                [self setRecentChatObjeFrom:YNmsg recentObj:recentChat];
                                recentChat.unReadCount = synListModel.unreadCount;
                                result=[YNContactManager saveRecentChatWithMessage:recentChat isFromRoamingSource:YES];
                                //将最后一条Messenger消息装入聊天记录数组里
                                if (![YNIMTool isEmptyString:synListModel.lastMsg]) {
                                    NSMutableDictionary*messageDic=[NSMutableDictionary dictionary];
                                    [messageDic setObject:synListModel.lastMsg forKey:@"msg"];
                                    [chatRecordArr addObject:messageDic];
                                }
                            }
                        }
                            break;
                        case YNBubbleMessageChatTypeGroupChat:
                        case YNBubbleMessageChatTypeDiscussion:
                        case YNBubbleMessageChatTypeProjectTeamChat:
                        case YNBubbleMessageChatTypeGroupChatVoice:
                        case YNBubbleMessageChatTypeDiscussionVoice:
                        case YNBubbleMessageChatTypeProjectTeamVoice:
                        {
                            //如果是群会话
                            YNmsg.fromUserId=[xmMessage to].user;
                            YNmsg.toUserId=[xmMessage from].user;
                            YNmsg.friendId=YNmsg.fromUserId;
                            /**HX** 如果是群会话类型，那选出项目组类型，然后重新对chatType赋值 **/
                            if (YNmsg.chatType == YNBubbleMessageChatTypeGroupChat) {
                                if ([YNmsg.friendId rangeOfString:ProjectTeamFlag].length > 0) {
                                    YNmsg.chatType = YNBubbleMessageChatTypeProjectTeamChat;
                                }
                            }
                            if (YNmsg.chatType == YNBubbleMessageChatTypeGroupChatVoice) {
                                if ([YNmsg.friendId rangeOfString:ProjectTeamFlag].length > 0) {
                                    YNmsg.chatType = YNBubbleMessageChatTypeProjectTeamVoice;
                                }
                            }
                            //先检查当前群id在本地能查到不，不能查到说明该该群已解散或是从数据库删除了
                            YNContactGroup *group = [YNContactManager queryUserNameByUserID:YNmsg.friendId chatType:YNmsg.chatType];
                            if ([YNIMTool isEmptyObject:group]) {
                                [YNContactManager deleteRecentChatWithRecentChatObject:YNmsg.friendId];
                            }else{
                                if ([YNmsg.toUserId isEqualToString:[YNIMmanager sharedInstance].userImId]) {
                                    YNmsg.friendName=@"我";
                                }
                                YNRecentChatObejct *recentChat= [YNMessagerReceiveHandle creatRecentChat:YNmsg];
                                recentChat.title = group.naturalName;
                                [self setRecentChatObjeFrom:YNmsg recentObj:recentChat];
                                recentChat.unReadCount = synListModel.unreadCount;
                                result=[YNContactManager saveRecentChatWithMessage:recentChat isFromRoamingSource:YES];
                                //将最后一条Messenger消息装入聊天记录数组里
                                if (![YNIMTool isEmptyString:synListModel.lastMsg]) {
                                    NSMutableDictionary*messageDic=[NSMutableDictionary dictionary];
                                    [messageDic setObject:synListModel.lastMsg forKey:@"msg"];
                                    [chatRecordArr addObject:messageDic];
                                }
                            }
                        }
                            break;
                        case YNBubbleMessageChatTypeBroadcast:
                        {
                            //广播消息
                            YNRecentChatObejct *recentChat= [YNMessagerReceiveHandle creatRecentChat:YNmsg];
                            NSString *covertStr = [YNMessage covertJsonWithHTML:YNmsg.body];
                            NSDictionary *messageBody = (NSDictionary*)[YNIMTool getJsonObjectFromJsonString:covertStr];
                            BOOL isBroadcast=NO;//是否是正确格式的广播消息
                            if (![messageBody isKindOfClass:[NSDictionary class]]) {
                                isBroadcast=YES;
                            }else{
                                if ([YNIMTool isEmptyObject:messageBody[@"messageType"]]) {
                                    isBroadcast=YES;
                                }else{
                                    //为平台发出的推送消息广播不要做处理
                                }
                            }
                            if (isBroadcast) {
                                //为pc端发的广播需要做处理
                                recentChat.title = recentChat.senderName;
                                recentChat.text = YNmsg.subject;
                                recentChat.unReadCount = synListModel.unreadCount;
                                result=[YNContactManager saveRecentChatWithMessage:recentChat isFromRoamingSource:YES];
                                /**HX** 装载记录未读广播的ids **/
                                [[YNIMmanager sharedInstance]clearBroadcastUnreadIds];
                                if (![YNIMTool isEmptyObject:synListModel.unreadMsgIds]) {
                                    NSArray *idsArray = [synListModel.unreadMsgIds componentsSeparatedByString:@","];
                                    if ([YNIMTool isEmptyArray:idsArray]) {
                                        [[YNIMmanager sharedInstance]addBroadcastUnreadMsgIds:synListModel.unreadMsgIds];
                                    }else{
                                        for (NSString*msgId in idsArray) {
                                            if (![YNIMTool isEmptyString:msgId]) {
                                                [[YNIMmanager sharedInstance]addBroadcastUnreadMsgIds:msgId];
                                            }
                                        }
                                    }
                                }
                                
                                //将最后一条Messenger消息装入聊天记录数组里-这个逻辑必须加在“装载记录未读广播的ids”之后，否则已读未读计数会出问题
                                if (![YNIMTool isEmptyString:synListModel.lastMsg]) {
                                    NSMutableDictionary*messageDic=[NSMutableDictionary dictionary];
                                    [messageDic setObject:synListModel.lastMsg forKey:@"msg"];
                                    [chatRecordArr addObject:messageDic];
                                }
                            }
                        }
                            break;
                        default:
                        {
                            
                            debugLog(@"其他类型消息");
                        }
                            break;
                    }
                }
            }
        }
    }else{
        //会话列表数据为空
    }
    //将聊天记录解析然后保存数据库
    if (![YNIMTool isEmptyArray:chatRecordArr]) {
        [YNContactManager parsingAndSaveRoamMessageWithInfo:chatRecordArr isMessageListData:YES isNewListPullData:NO];
    }
    return result;
}

/**
 组装最近会话列表对象
 
 @param YNmsg 消息对象
 @param recentChat 需要组装的最近会话对像
 */
+(void)setRecentChatObjeFrom:(YNMessage*)YNmsg recentObj:(YNRecentChatObejct*)recentChat{
    //将消息分段转成数组, 然后再转成Json字符串保存数据库
    NSArray *messageArray=[YNMessagerReceiveHandle parserMessageStr:YNmsg.text messageBody:YNmsg.message];
    //消息json化
    if (messageArray.count)
    {
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:messageArray options:NSJSONWritingPrettyPrinted error:nil];
        YNmsg.text = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        
        //判断是不是图文混排
        BOOL isPic = [[messageArray lastObject] boolValue];
        if (isPic)
        {
            //是就改变消息媒体类型
            NSUInteger imgCount = [[messageArray objectAtIndex:messageArray.count - 3] integerValue];
            if (imgCount)
            {
                //是就改变消息媒体类型
                YNmsg.messageMediaType = YNBubbleMessageMix;
            }
            else
            {
                YNmsg.messageMediaType = YNBubbleMessageText;
            }
        }
    }
    else
    {
        YNmsg.text = [YNIMTool jsonStringWithObject:YNmsg.text];
    }
    recentChat.text = YNmsg.text;
    recentChat.messageType = YNmsg.messageMediaType;
}

/**
 * pram dic  包含
 *      sendTiem 发送时间
 *      type     消息类型
 *      from     消息发送者
 *      body     消息体
 *      recipient   广播才有的消息体(广播消息信息)
 *      subject     广播才有(广播主题)
 **/
//保存到通知表
+ (void)insertNotificationWithInfo:(NSDictionary *)dic inDatabase:(FMDatabase *)db packetId:(NSString *)packetId jid:(XMPPJID *)jid bodyDictionary:(NSDictionary *)body bodyStr:(NSString *)bodyStr
{
    
    //创建通知
    YNBroadcastNotificationChat *notification = [[YNBroadcastNotificationChat alloc] init];
    notification.packetId = packetId;
    notification.subject = [dic objectForKey:@"subject"];
    notification.fromUserNo = jid.user;
    notification.toUserNo = [YNIMmanager sharedInstance].userImId;
    notification.content = [body objectForKey:@"content"];
    notification.link = @"";
    notification.mTime = [dic objectForKey:@"sendTime"];
    notification.senderName = [body objectForKey:@"sendName"];
    notification.broadcastNotificationType = [[body objectForKey:@"messageType"] intValue];;
    notification.recipient = nil;
    notification.sourceTerminal = [[body objectForKey:@"sourceTerminal"] intValue];
    notification.isRead = 0;
    
    [notification insertBroadcastNotificationInDatabase:db];
}


@end

